Reputation: 27
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
Reputation: 25434
You can't assume which of locks will be invoked first. Let us consider two options:
Upvotes: 1
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:
Thread(pulseWaitFun).Start();
lock (locker)
, uncontested so the lock is immediately grantedMonitor.Pulse(locker);
, the Pulse is wasted because nobody is waiting. lock()
in the main methodYou probably want a Thread.Sleep(100)
inside Main(), after starting the Thread.
Upvotes: 3