John
John

Reputation: 193

About pthread_cond_wait

For the following code:

f1()
{
    pthread_mutex_lock(&mutex); //LINE1 (thread3 and thread4)
    pthread_cond_wait(&cond, &mutex);  //LINE2  (thread1 and thread2)
    pthread_mutex_unlock(&mutex); 
}

f2()
{
    pthread_mutex_lock(&mutex); 
    pthread_cond_signal(&cond);  //LINE3 (thread5)
    pthread_mutex_unlock(&mutex); 
}

Assume thread1 and thread2 are waiting at LINE2, thread3 and thread4 are blocked at LINE1. When thread5 executes LINE3, which threads will run first? thread1 or thread2? thread3 or thread4?

Upvotes: 0

Views: 58

Answers (1)

user3793679
user3793679

Reputation:

When thread5 signals the condition, either thread1 or thread2, or both, will be released from waiting, and will wait until the mutex can be locked... which won't be until after thread5 unlocks it.

When thread5 then unlocks the mutex, one of the threads waiting to lock the mutex will be able to do so. My reading of POSIX reveals only that the order in which threads waiting to lock will proceed is "under defined", though higher priority threads may be expected to run first. How things are scheduled is largely system dependent.

If you need threads to run in a particular order, then you need to arrange that for yourself.

Upvotes: 1

Related Questions