[Mono-dev] SemaphoreSlim implementation

Rodrigo Kumpera kumpera at gmail.com
Mon Apr 8 16:18:43 UTC 2013


On Thu, Apr 4, 2013 at 8:18 PM, Weeble <clockworksaint at gmail.com> wrote:

> 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?
>

Yes, looks like our implementation could use some optimization.


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?
>

Yes, it's confusing.



> 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?
>

Yes, probably. Other optimizations for this are posible too.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.ximian.com/pipermail/mono-devel-list/attachments/20130408/710e59d6/attachment.html>


More information about the Mono-devel-list mailing list