pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cv = PTHREAD_COND_INITIALIZER;
void thread_1() {
pthread_mutex_lock(&mutex);
some_cond = true;
pthread_cond_signal(&cv);
pthread_mutex_unlock(&mutex);
}
void thread_2() {
pthread_mutex_lock(&mutex);
while (!some_cond)
pthread_cond_wait(&cv, &mutex);
printf("test"); // After signaling from thread_1, does this get ran after?
pthread_mutex_unlock(&mutex);
}
Let's say that thread_2 calls pthread_cond_wait.
Thread_1 comes along then does pthread_cond_signal.
I understand that thread_2 will be blocked when pthread_cond_wait is called, and unlock its mutex. However, I am confuse on which line of code will run in thread_2 after thread_1 calls signal.
In thread_2 when its woken up, does it start from the beginning where thread_2 now has access to the mutex, then locks it, then checks the while condition again, and sees that its true now and prints test?
Or does thread_2 get access to its mutex, then locks it and then the print("test") is ran after (ignoring the while condition)?
The several other examples are all good, but they also all seem to gloss over what I take to be the OP's key point of confusion.
I am confuse on which line of code will run in thread_2 after thread_1 calls signal.
There is no magic here. pthread_cond_wait()
is a function, and it behaves like one. When its wait is over, and it has reacquired the mutex, it returns to its caller. Control proceeds normally from there, just as it would after any other function call returns.
In this particular case, the function call is the sole statement in the body of a while
loop, so the next thing that happens after the call returns will be the while
condition being reevaluated.
Note that pthread_cond_wait
's caller can and should check the return value to catch and handle cases where it indicates that an error has occurred, just as should be done with other functions that indicate error conditions via their return values.