Reputation: 41
I have the following code:
typedef struct {
...
volatile int i_lines_completed;
pthread_mutex_t mutex;
q265_pthread_cond_t cv;
...
}q265_picture_t;
void q265_frame_cond_broadcast( q265_picture_t *frame, int i_lines_completed )
{
pthread_mutex_lock( &frame->mutex );
frame->i_lines_completed = i_lines_completed;
pthread_cond_broadcast( &frame->cv );
pthread_mutex_unlock( &frame->mutex );
}
void q265_frame_cond_wait( q265_picture_t *frame, int i_lines_completed )
{
pthread_mutex_lock( &frame->mutex );
while( frame->i_lines_completed < i_lines_completed )
pthread_cond_wait( &frame->cv, &frame->mutex );
pthread_mutex_unlock( &frame->mutex );
}
The use case is:
More than one thread could call q265_frame_cond_wait
to request that the frame have the required i_lines_completed
while there is only one thread call the q265_frame_cond_broadcast
to broadcast the i_lines_completed
.
The question is:
Is it valid that several threads call the q265_frame_cond_wait
synchronously?
When the certain thread call the q265_frame_cond_broadcast
,
Another problem: But is it right that two pthread_cond_t share only one mutex? For example, the following code, the two pthread_cond_t is_fill and is_empty share the only one mutex, and threads will possibly call q265_framelist_cond_wait0 and q265_framelist_cond_wait1 synchronously.
typedef struct {
...
volatile int i_size;
pthread_mutex_t mutex;
q265_pthread_cond_t is_fill, is_empty;
...
}q265_picture_list_t;
void q265_framelist_cond_wait0( q265_picture_list_t *framelist)
{
pthread_mutex_lock( &framelist->mutex );
while( framelist->i_size <= 0)
pthread_cond_wait( &framelist->is_fill, &framelist->mutex );
pthread_mutex_unlock( &framelist->mutex );
}
void q265_framelist_cond_wait1( q265_picture_list_t *framelist)
{
pthread_mutex_lock( &framelist->mutex );
while( framelist->i_size == max_size)
pthread_cond_wait( &framelist->is_empty, &framelist->mutex );
pthread_mutex_unlock( &framelist->mutex );
}
Upvotes: 4
Views: 386
Reputation: 136515
The question is: Is it valid that several threads call the q265_frame_cond_wait synchronously
Multiple threads can call q265_frame_cond_wait
, there is no race condition.
q265_frame_cond_broadcast
, will all the waiting thread get the mutex synchronously?
pthread_cond_broadcast
wakes up all threads currently waiting on the condition variable. Only one thread can lock a mutex at a time, so that these woken up threads queue up on locking the mutex.
Or they must compete to get the mutex?
Conceptually yes, pthread_cond_wait
has to lock the mutex on return. And this is known as thundering herd problem.
Linux solves this problem by moving the queue of waiters on the condition variable to the queue of waiters on the mutex to avoid waking up threads that would then immediately be blocked on the mutex. This is known as wait morphing.
Upvotes: 2