Skip to content

Instantly share code, notes, and snippets.

@notanaverageman
Created July 11, 2021 12:02
Show Gist options
  • Select an option

  • Save notanaverageman/c4225d73e69b0e3168037c93dc6ffbd9 to your computer and use it in GitHub Desktop.

Select an option

Save notanaverageman/c4225d73e69b0e3168037c93dc6ffbd9 to your computer and use it in GitHub Desktop.
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