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 );
}
使用情况如下:
当只有一个线程调用
q265_frame_cond_broadcast
广播 i_lines_completed
时,会有多个线程调用 q265_frame_cond_wait
请求帧具有所需的 i_lines_completed
。问题是:
是否有效让多个线程同时调用
q265_frame_cond_wait
?当某个线程调用
q265_frame_cond_broadcast
时,
- 所有等待的线程是否都同步获取互斥锁?
- 还是它们必须竞争以获取互斥锁?
但两个 pthread_cond_t 是否只共享一个互斥锁?例如,以下代码中,两个 pthread_cond_t is_fill 和 is_empty 共享唯一的互斥锁,并且线程可能会同时调用 q265_framelist_cond_wait0 和 q265_framelist_cond_wait1。
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 );
}
pthread_cond_broadcast
,那么就意味着多个线程可以等待一个条件。当线程在pthread_cond_wait
中等待时,互斥锁将被解锁,因此在等待期间不会出现问题。在此之后和之前,它们将必须相互等待以释放互斥锁。 - Hayt