Advertisement
GeneralGDA

Barrier

Apr 19th, 2023 (edited)
731
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.81 KB | None | 0 0
  1. public sealed class BarrierSlim
  2. {
  3.     private readonly int _threshold;
  4.     private int _arrived;
  5.  
  6.     private readonly SemaphoreSlim _gate;
  7.     private readonly SemaphoreSlim _mutex;
  8.  
  9.     public BarrierSlim(int count)
  10.     {
  11.         _threshold = count;
  12.         _gate = new SemaphoreSlim(initialCount: 0, maxCount: count);
  13.         _mutex = new SemaphoreSlim(initialCount: 1, maxCount: 1);
  14.     }
  15.  
  16.     public async Task ArriveAsync()
  17.     {
  18.         await _mutex.WaitAsync();
  19.  
  20.         _arrived++;
  21.  
  22.         if (_threshold == _arrived)
  23.         {
  24.             for (int i = 0; i < _threshold; i++)
  25.             {
  26.                 _gate.Release();
  27.             }
  28.             _mutex.Release();
  29.         }
  30.         else
  31.         {
  32.             _mutex.Release();
  33.             await _gate.WaitAsync();
  34.         }
  35.     }
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement