[Mono-dev] SemaphoreSlim implementation

Weeble clockworksaint at gmail.com
Fri Apr 5 00:18:53 UTC 2013


I was looking at SemaphoreSlim because it seemed to be causing us
trouble. I think I identified our problem and submitted it as bug
11598: https://bugzilla.xamarin.com/show_bug.cgi?id=11598

However, beyond the issue I describe there, I'm a bit unsure about a
few aspects of the implementation. Could anybody look at it and tell
me whether my concerns are warranted?

https://github.com/mono/mono/blob/master/mcs/class/corlib/System.Threading/SemaphoreSlim.cs

1. It's not clear what benefit it has over Semaphore. In .NET - as I
understand it - the point of SemaphoreSlim is that in the case of low
contention it doesn't actually use a WaitHandle and so avoids
expensive calls into the kernel. It's only as a last resort that it
actually allocates a WaitHandle and blocks on it. However, Mono's
SemaphoreSlim always allocates a ManualResetEvent up-front, and
signals it on every Release. Doesn't a ManualResetEvent have a kernel
object and involve a context switch to signal it? Doesn't this nullify
the only benefit of SemaphoreSlim over Semaphore?

2. I don't understand the logic to decide how long to block for after
spinning has failed. It seems to wait between 1 and deepSleepTime(=20)
milliseconds. If a timeout has been specified it waits for the event
until the timeout expires, clamped between 1 and 20 milliseconds. If
no timeout has been specified (millisecondsTimeout=-1) it seems to
always wait 1 millisecond. It seems that it would make more sense in
that case to wait for the longest time possible, not the shortest.
Have I misunderstood the code?

3. I don't understand why it sets an upper limit on the wait time at
all. Is that the only way to support cancellation tokens? If no
cancellation token were provided, would it be better to wait as long
as possible?

Regards,

Weeble.


More information about the Mono-devel-list mailing list