Note that there are some explanatory texts on larger screens.

plurals
  1. POMonitor.Pulse in C# appears suboptimal : must be in lock scope
    text
    copied!<p>spoiler note: the question is the last phrase.</p> <p>In C#, the classical pattern to use a condition variable is like this:</p> <pre><code>lock (answersQueue) { answersQueue.Enqueue(c); Monitor.Pulse(answersQueue); // condition variable "notify one". } </code></pre> <p>and some other thread:</p> <pre><code>lock (answersQueue) { while (answersQueue.Count == 0) { // unlock answer queue and sleeps here until notified. Monitor.Wait(answersQueue); } ... } </code></pre> <p>that's an example taken from my code. if I place the Pulse outside of the lock scope, it doesn't compile. however, it is the correct way: c.f:</p> <p><a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms686903(v=vs.85).aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/windows/desktop/ms686903(v=vs.85).aspx</a> and: <a href="http://www.installsetupconfig.com/win32programming/threadprocesssynchronizationapis11_7.html" rel="nofollow">http://www.installsetupconfig.com/win32programming/threadprocesssynchronizationapis11_7.html</a> (search for "inside")</p> <p>And indeed it is idiotic to signal the sleeping thread when you still are in your critical section. Because the sleeping thread CAN'T wake up (not immediately), BECAUSE it is INSIDE a criticial section as well !</p> <p>Therefore, I hope that .NET or C# Pulse call is actually just flagging the lock object, so that when it goes out of scope it actually "pulses" the condition variable at this moment. Because otherwise, it would have an optimality issue.</p> <p>So how come the design of the Monitor object was chosen to be that way ?</p> <p>Edit:</p> <p>I found the answer in this paper: <a href="http://research.microsoft.com/pubs/64242/implementingcvs.pdf" rel="nofollow">http://research.microsoft.com/pubs/64242/implementingcvs.pdf</a> section "Optimising Signal and Broadcast" and the previous section about NT kernel and how to make Condition Variable on top of Semaphores, which is the reason for introducing the "darned queues". NOW that makes me a better engineer.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload