Created
July 11, 2021 12:02
-
-
Save notanaverageman/c4225d73e69b0e3168037c93dc6ffbd9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System.Threading; | |
| using System.Threading.Tasks; | |
| namespace Namespace | |
| { | |
| // Inspired by https://stackoverflow.com/a/961904/3670437 | |
| public class FifoMutexAsync | |
| { | |
| private readonly SemaphoreSlim _semaphore; | |
| private int _ticketsCount; | |
| private int _ticketToRide; | |
| public FifoMutexAsync() | |
| { | |
| _semaphore = new SemaphoreSlim(1, 1); | |
| _ticketsCount = 0; | |
| _ticketToRide = 1; | |
| } | |
| public async Task Acquire() | |
| { | |
| int myTicket = Interlocked.Increment(ref _ticketsCount); | |
| await _semaphore.WaitAsync(); | |
| while (true) | |
| { | |
| if (myTicket == _ticketToRide) | |
| { | |
| return; | |
| } | |
| _semaphore.Release(); | |
| await _semaphore.WaitAsync(); | |
| } | |
| } | |
| public void Release() | |
| { | |
| Interlocked.Increment(ref _ticketToRide); | |
| _semaphore.Release(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment