Can pthread_cond_wait() always win the competition in locking a mutex?

后端 未结 2 979
面向向阳花
面向向阳花 2021-01-07 11:36

This question is regarding the pthread tutorial in llnl. Say there are three threads.

Thread 1:

pthread_mutex_lock(&mutex)
do_s         


        
2条回答
  •  悲哀的现实
    2021-01-07 12:10

    My question is: is there any guarantee that Tread3 will always win in the competition?

    No such guarantees. From POSIX:

    The pthread_cond_signal() function shall unblock at least one of the threads that are blocked on the specified condition variable cond (if any threads are blocked on cond).

    If more than one thread is blocked on a condition variable, the scheduling policy shall determine the order in which threads are unblocked. When each thread unblocked as a result of a pthread_cond_broadcast() or pthread_cond_signal() returns from its call to pthread_cond_wait() or pthread_cond_timedwait(), the thread shall own the mutex with which it called pthread_cond_wait() or pthread_cond_timedwait(). The thread(s) that are unblocked shall contend for the mutex according to the scheduling policy (if applicable), and as if each had called pthread_mutex_lock().

    (Emphasis mine).

    If not then after Tread2 do_something..., the condition variable may be changed, then when Tread3 gets to lock the mutex, the condition variable is different from what it expects.

    If the order of execution of threads matter then you probably need to rewrite your code.

提交回复
热议问题