0

I'm in the wild and have stumbled upon the following code snippet in a constructor:

            lock (_lock)
                while (0 != x)
                    Monitor.Wait(_lock);

I'm not really sure what this is doing, and the purpose of it. I've read about Monitor.Wait,

When a thread calls Wait, it releases the lock on the object and enters the object's waiting queue. The next thread in the object's ready queue (if there is one) acquires the lock and has exclusive use of the object.

So let's say I am the thread that locked _lock. While (x != 0), where x is most likely being updated by another thread. I'm releasing x to be updated, it is updated by the next thread in the queue, and then I am free to check x != 0 after the other thread has released its lock over x?

Furthermore, what if there is no thread in the ready queue? I see Monitor.Pulse(_lock) being called in other parts of the code (a separate function) as an event raised method.

            lock (_lock)
                Monitor.Pulse(_lock);

Thank you in advance for explaining.

  • 1
    The code appears to aquire a lock, and then continue to release and aquire the lock until `x == 0`. – Rufus L Mar 04 '20 at 18:24
  • @RufusL Is it doing so such that another thread being blocked by the lock can go in and make changes to `x`? –  Mar 04 '20 at 18:29
  • Does this answer your question? [C# : Monitor - Wait,Pulse,PulseAll](https://stackoverflow.com/questions/1559293/c-sharp-monitor-wait-pulse-pulseall) – MKR Mar 04 '20 at 18:39
  • @RufusL, Re, "...and then continues to release and acquire..." When it's correctly used, there will not be many cycles of release and acquire. The most important thing that the `Wait(_lock)` call does is, it _waits_. Specifically, it waits until some other thread calls `Monitor.Pulse(_lock)`. The other thread should only ever do that after it has changed the value of `x`. https://learn.microsoft.com/en-us/dotnet/api/system.threading.monitor?redirectedfrom=MSDN&view=netframework-4.8#Pulse – Solomon Slow Mar 04 '20 at 18:51
  • @TeeZadAwk Presumably, yes. As @SolomonSlow mentioned, the loop probably won't execute more than a few times, but it really depends on how many other tasks are aquiring locks on the `_lock` object that aren't changing the value of `x` – Rufus L Mar 04 '20 at 19:45

0 Answers0