-
Notifications
You must be signed in to change notification settings - Fork 689
Expand file tree
/
Copy pathLeaderFollowerBarrier.cs
More file actions
81 lines (71 loc) · 2.96 KB
/
Copy pathLeaderFollowerBarrier.cs
File metadata and controls
81 lines (71 loc) · 2.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Garnet.common
{
/// <summary>
/// Synchronization primitive for coordinating a leader task with multiple participant tasks in a cyclic pattern.
/// The leader signals work readiness, waits for all participants to complete, then the cycle repeats.
/// Participants wait for work signal, process, signal completion, then wait for reset before next cycle.
/// </summary>
public sealed class LeaderFollowerBarrier
{
readonly int participantCount;
readonly SemaphoreSlim workReady = new(0);
readonly SemaphoreSlim workCompleted = new(0);
readonly SemaphoreSlim resetReady = new(0);
/// <summary>
/// Initializes a new instance of the <see cref="LeaderFollowerBarrier"/> class.
/// </summary>
/// <param name="participantCount">Number of participant tasks that will process work.</param>
public LeaderFollowerBarrier(int participantCount)
{
ArgumentOutOfRangeException.ThrowIfLessThan(participantCount, 1);
this.participantCount = participantCount;
}
static TimeSpan ProcessTimeSpan(TimeSpan timeout)
=> timeout == default ? Timeout.InfiniteTimeSpan : timeout;
/// <summary>
/// Leader: Waits for all participants to complete, then resets for next cycle.
/// </summary>
public bool WaitCompleted(TimeSpan timeout = default, CancellationToken cancellationToken = default)
{
var waitTimeout = ProcessTimeSpan(timeout);
for (var i = 0; i < participantCount; i++)
{
if (!AsyncUtils.BlockingWait(workCompleted.WaitAsync(waitTimeout, cancellationToken)))
return false;
}
return true;
}
/// <summary>
/// Leader: Release participants that are waiting inside <see cref="SignalCompleted"/>
/// so they can proceed to the next cycle.
/// </summary>
public void Release() => resetReady.Release(participantCount);
/// <summary>
/// Participant: Waits for work signal from leader.
/// </summary>
public async Task WaitReadyWorkAsync(CancellationToken cancellationToken = default)
{
await workReady.WaitAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Leader: Signals all participants that work is ready.
/// </summary>
public void SignalWorkReady()
{
workReady.Release(participantCount);
}
/// <summary>
/// Participant: Signals completion and waits for leader to reset.
/// </summary>
public void SignalCompleted(CancellationToken cancellationToken = default)
{
workCompleted.Release();
resetReady.Wait(cancellationToken);
}
}
}