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.