0
votes

Suppose our threads look something like this:

thread1:

Lock(mutex) {
    //code
    if(something)
        signal(condition_var);
    //code
} //unlocks

thread2:

Lock(mutex) {
    //code
    while(something)
        wait(mutex, condition_var);
    //code
} //unlocks

1) Suppose the signal in thread1 gets executed and then context switch happens before mutex gets unlocked.

2) thread2 which was waiting on condition_var, attempts to continue but mutex is still locked. Now it will keep waiting i guess. Suppose context happens again.

3) thread1 now finishes and unlocks mutex.

How will wait in thread2 behave now, as anything won't signal it again, how will thread2 stop waiting?

1
Locked mutex doesn't prevent being awaken on conditional variable when someone calls signal(). In that case, instead of waiting on condition variable, thread begins to wait on mutex. This waiting ends when someone unlock mutex(at the step 3 in you example).Tsyvarev
Yes, you are right. This was mentioned in spurious wake ups section of the videos lectures i am watching. I did'nt get it that time. Thanks :)nishantbhardwaj2002

1 Answers

0
votes

When the condition variable is signalled, the thread waiting on that condition variable will be put into a state where it is trying to re-acquire the mutex and then proceed. It doesn't need to be signalled again after this - if the mutex is released eventually, it will proceed (it's now just like it's waiting in a normal attempt to lock the mutex).