user2140086
user2140086

Reputation: 27

c#: pulse and wait

I have a question regarding the pulse and wait of monitor class. Following is the extract of code. My question is will the code be stuck at

// <<-----------

untill locker becomes free ?

     {
        check = false;
        new Thread(pulseWaitFun).Start();

        Console.Writeline("Threading tutorial");

        lock (locker) // <<-----------
        {
            check = true;
            Monitor.Pulse(locker);
        }
        Console.ReadLine();
    }

    static void pulseWaitFun()
    {
        lock (locker)
        {
            if(check != true)
            {
                Thread.Sleep(20000);
                Monitor.Wait(locker);

            }
        }

        Console.WriteLine("Woken !!");
    }

second question, after Monitor.Pulse(locker); what will be following sequence of execution ?

Upvotes: 1

Views: 245

Answers (2)

Ryszard Dżegan
Ryszard Dżegan

Reputation: 25434

You can't assume which of locks will be invoked first. Let us consider two options:

  • Lock in main method is reached first. Check is set to true. Invoking Pulse has no effect. Next main thread releases the lock and the second thread can aquire it in pulseWaitFun.
  • Lock in pulseWaitFun method is reached first. Check is false, so thread is sleeping and then waits for signal which causes realising the lock. Now the main thread aquires the lock and pulses. Then releases the lock. After that pulseWaitFun can proceed.

Upvotes: 1

Henk Holterman
Henk Holterman

Reputation: 273244

My q is will the code be stuck at ... untill locker becomes free ?

Yes, but the lock can be released by exiting a lock() {} block OR by entering a Wait().

after Monitor.Pulse(locker); what will be following sequence of execution ?

In your code the sequence will most likely be:

  1. Thread(pulseWaitFun).Start();
  2. lock (locker) , uncontested so the lock is immediately granted
  3. Monitor.Pulse(locker); , the Pulse is wasted because nobody is waiting.
  4. exit lock() in the main method
  5. The 2nd Thread starts executing...

You probably want a Thread.Sleep(100) inside Main(), after starting the Thread.

Upvotes: 3

Related Questions