|
| 1 | +# Thread Coordination Primitives |
| 2 | + |
| 3 | +## Barrier |
| 4 | + |
| 5 | +`Barrier` allows multiple threads to execute in same phase and not moving to next phase until all participant signaled. |
| 6 | + |
| 7 | +- `Barrier` must have a specified count of participant threads |
| 8 | +- `barrier.SignalAndWait()` increases the inner counter in `Barrier` |
| 9 | +- phase is completed when the number of threads signaled reaches **the count** of barrier |
| 10 | +- new phase is started when any thread signaled made the counter increased from 0 to 1 |
| 11 | +- each thread would not continue until sufficient count of threads have signaled(participated) |
| 12 | + |
| 13 | +```cs |
| 14 | +// you may register a event on phase finished // [!code highlight] |
| 15 | +Barrier barrier = new(3, b => { // [!code highlight] |
| 16 | + Console.WriteLine($"phase {b.CurrentPhaseNumber} has finished"); // [!code highlight] |
| 17 | +}); // [!code highlight] |
| 18 | +
|
| 19 | +var tasks = Enumerable.Range(1, 3).Select(_ => { |
| 20 | + return Task.Run(() => { |
| 21 | + // notifying barrier that this thread has entered |
| 22 | + // the counter inside increments |
| 23 | + // and all participants would continue when the count hits limit |
| 24 | + // and the count would reset to the sepcified |
| 25 | + barrier.SignalAndWait(); // signal for the first time to enter phase 0 // [!code highlight] |
| 26 | + Console.WriteLine($"Task {Task.CurrentId} is handling phase {barrier.CurrentPhaseNumber}"); |
| 27 | + barrier.SignalAndWait(); // signal again indicating to enter phase 1 |
| 28 | + }); |
| 29 | +}); |
| 30 | + |
| 31 | +Task.WaitAll(tasks); |
| 32 | + |
| 33 | +// phase 0 has finished |
| 34 | +// Task 1 is handling phase 1 |
| 35 | +// Task 3 is handling phase 1 |
| 36 | +// Task 2 is handling phase 1 |
| 37 | +// phase 1 has finished |
| 38 | +``` |
| 39 | + |
| 40 | +## CountDownEvent |
| 41 | + |
| 42 | +`CountDownEvent` is a primitive to block certain threads until a count down has reached |
| 43 | + |
| 44 | +```cs |
| 45 | +CountdownEvent @event = new(3); |
| 46 | + |
| 47 | +var waiting = Task.Run(() => { |
| 48 | + Console.WriteLine("This task is waiting for count down completion"); |
| 49 | + @event.Wait(); // blocking until count down finished // [!code highlight] |
| 50 | + Console.WriteLine("Task finished after count down"); |
| 51 | +}); |
| 52 | + |
| 53 | + |
| 54 | +var countdown = Enumerable.Range(1, 3).Select(_ => { |
| 55 | + return Task.Run(() => { |
| 56 | + Thread.Sleep(1000); |
| 57 | + Console.WriteLine("count down"); |
| 58 | + @event.Signal(); |
| 59 | + }); |
| 60 | +}); |
| 61 | + |
| 62 | +Task.WaitAll([waiting, .. countdown]); |
| 63 | + |
| 64 | +// This task is waiting for count down finished |
| 65 | +// count down |
| 66 | +// count down |
| 67 | +// count down |
| 68 | +// Task finished after count down |
| 69 | +``` |
| 70 | + |
| 71 | +> [!NOTE] |
| 72 | +> You may increase a count dynamically using `AddCount` or `TryAddCount` |
| 73 | +
|
| 74 | +## ManualResetEventSlim |
| 75 | + |
| 76 | +`ManualResetEventSlim` behaves somewhat like a one-time counter that counts up to 1, it can be used to implement a continuation. |
| 77 | + |
| 78 | +```cs |
| 79 | +// optionally set initialState impling whther the event is already signaled |
| 80 | +ManualResetEventSlim @event = new(initialState: false); |
| 81 | + |
| 82 | +var waiting = Task.Run(() => { |
| 83 | + Console.WriteLine("waiting for one time signal"); |
| 84 | + @event.Wait(); // [!code highlight] |
| 85 | + Console.WriteLine("post action triggered"); |
| 86 | + @event.Wait(); |
| 87 | + if (@event.Wait(1000)) { } |
| 88 | + Console.WriteLine("still reachable since the event has to be reset manually to regain blocking"); // [!code highlight] |
| 89 | + // reset the count to regain blocking |
| 90 | + @event.Reset(); // [!code warning] |
| 91 | + @event.Wait(); // infinite blocking since now no signal would be sent again // [!code warning] |
| 92 | +}); |
| 93 | + |
| 94 | +var count = Task.Run(() => { |
| 95 | + Console.WriteLine("perform something and then signal"); |
| 96 | + @event.Set(); |
| 97 | +}); |
| 98 | + |
| 99 | +waiting.Wait(); |
| 100 | +``` |
| 101 | + |
| 102 | +> [!NOTE] |
| 103 | +> Use `AutoResetEvent` if auto reset on count is required which automatically reset state when wait succeeded |
| 104 | +>```cs |
| 105 | +>AutoResetEvent @event = new(initialState: false); |
| 106 | +> |
| 107 | +>var waiting = Task.Run(() => { |
| 108 | +> Console.WriteLine("waiting for one time signal"); |
| 109 | +> _ = @event.WaitOne(); // [!code highlight] |
| 110 | +> Console.WriteLine("post action triggered"); |
| 111 | +> _ = @event.WaitOne(); // would hang here forever since state was reset automatically // [!code warning] |
| 112 | +> Console.WriteLine("not reachable!!"); // [!code warning] |
| 113 | +>}); |
| 114 | +> |
| 115 | +>var countdown = Task.Run(() => { |
| 116 | +> Console.WriteLine("perform something and then signal"); |
| 117 | +> _ = @event.Set(); |
| 118 | +>}); |
| 119 | +> |
| 120 | +>waiting.Wait(); |
| 121 | +>``` |
| 122 | +
|
| 123 | +## SemaphoreSlim |
| 124 | +
|
| 125 | +`SemaphoreSlim` allows limited count of multiple threads to execute concurrently and release the hold dynamically. |
| 126 | +
|
| 127 | +- `semaphore.Wait(...)`: would block current thread when count is 0, so you should release to increase the count somewhere to make sure it continues |
| 128 | +- `semaphore.Release(int?)`: to release specific count so other threads could continue |
| 129 | + - returns a previous count of semaphore |
| 130 | + - `maxCount` on constructor came into play since release is a manual control. |
| 131 | + - when `maxCount` was reached, `SemaphoreFullException` would be thrown. |
| 132 | +
|
| 133 | +So the *count* is essentially a limit of how many threads could continue for now, if the count reaches 0, all other threads not entered semaphore have to wait. |
| 134 | +Remember to *release* to get the count back so other thread could enter semaphore later. |
| 135 | +
|
| 136 | +```cs |
| 137 | +using System.Diagnostics; |
| 138 | +using System.Runtime.ConstrainedExecution; |
| 139 | +
|
| 140 | +// three in a row, can dynamically increase the count to 10 at most |
| 141 | +SemaphoreSlim semaphore = new(initialCount: 3, maxCount: 10); |
| 142 | +
|
| 143 | +int shared = 0; |
| 144 | +
|
| 145 | +var tasks = Enumerable.Range(1, 100).Select(n => { |
| 146 | + return Task.Run(() => { |
| 147 | +
|
| 148 | + semaphore.Wait(); // would block when count is 0 // [!code highlight] |
| 149 | +
|
| 150 | + Thread.Sleep(1000); |
| 151 | +
|
| 152 | + Console.WriteLine(n); // order is not guaranteed by semaphore |
| 153 | + Interlocked.Add(ref shared, 1); // multiple thread would still come in so protection is neeeded |
| 154 | +
|
| 155 | + _ = semaphore.Release(); // [!code highlight] |
| 156 | + }); |
| 157 | +}); |
| 158 | +
|
| 159 | +Task.WaitAll(tasks); |
| 160 | +
|
| 161 | +Debug.Assert(shared is 100); |
| 162 | +``` |
0 commit comments