Yair Nevet
Yair Nevet

Reputation: 13003

Code doesn't work as desired without signaling with Wait and Pulse

Given the following code, the blocking-condition is changing when I hit the Enter key:

class Program
{
    static readonly object _locker = new object();
    static bool _go;
    static void Main()
    {
        new Thread(Work).Start();
        Console.ReadLine();
        lock (_locker)
        { 
            _go = true;
            Monitor.Pulse(_locker);
        }
    }
    static void Work()
    {
        lock (_locker)
            while (!_go)
                Monitor.Wait(_locker);
        Console.WriteLine("Woken!!!");
    }
}

But if I don't use Monitor.Wait and Monitor.Pulse then Console.WriteLine("Woken!!!"); never been called, it's seems like the _go flag is not changing.

Does anyone know why?

Upvotes: 0

Views: 77

Answers (2)

aguyngueran
aguyngueran

Reputation: 1321

_go is never changed without Monitor.Wait becasue thread Work method locks _locker and that's why the main thread cannot acquire the same lock in order to change _go value

Upvotes: 1

Nick Butler
Nick Butler

Reputation: 24383

You need to call Pulse to wake up the work thread if it is in Monitor.Wait

I wrote an article about the correct way to use Wait and Pulse:

Thread synchronization: Wait and Pulse demystified

Upvotes: 0

Related Questions