Skip to content
ikopylov edited this page Dec 27, 2014 · 6 revisions

Qoollo SemaphoreLight

Semaphore is a synchronization primitive that control the access to limited resource.

BCL already have 2 implementations of this primitive: System.Threading.Semaphore and System.Threading.SemaphoreSlim. But they are not as fast as possible. System.Threading.Semaphore use the Windows semaphore under cover so it should call WinAPI which gives an overhead. System.Threading.SemaphoreSlim is support async Wait method (which require additional checks) and also badly implemented.

SemaphoreLight provide a similar API but outperform standard implementations all the time. This is because it works in lock-free manner when possible.

Sample code:

var sem = new SemaphoreLight(0);

// Release and wait
sem.Release();
sem.Wait();

// Release and wait with timeout and CancellationToken
sem.Release();
sem.Wait(0, CancellationToken.None);

Performance

All tests performed on CPU with 8 cores. Every iteration has pause for 10 processor ticks (Thread.Spin(10)).

Release thread count / Wait thread count SemaphoreLight SemaphoreSlim Semaphore
1 / 1 980 ms 1700 ms 3670 ms
8 / 8 650 ms 1700 ms 3500 ms
1 / 8 1750 ms 3700 ms 6900 ms
4 / 16 870 ms 2800 ms 4800 ms
8 / 1 520 ms 1240 ms 3450 ms
16 / 4 550 ms 1300 ms 3200 ms