【问题标题】:about the pthread_cond_wait?关于 pthread_cond_wait?
【发布时间】:2017-01-08 05:18:13
【问题描述】:

我有以下代码:

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_wait 来请求帧具有所需的i_lines_completed,而只有一个线程调用q265_frame_cond_broadcast 来广播i_lines_completed

问题是:

多个线程同时调用q265_frame_cond_wait是否有效?

当某个线程调用q265_frame_cond_broadcast时,

  • 所有等待的线程会同步获取互斥锁吗?
  • 或者他们必须竞争以获得互斥锁?

另一个问题: 但是两个 pthread_cond_t 只共享一个互斥锁对吗?比如下面的代码,两个pthread_cond_t is_fill 和is_empty 共用一个mutex,线程可能会同步调用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 中时,互斥锁将被解锁,因此在它们等待时没有问题。之后和之前他们将不得不等待对方释放互斥锁

标签: c++ c multithreading pthreads


【解决方案1】:

问题是:多个线程同步调用q265_frame_cond_wait是否有效

多个线程可以调用q265_frame_cond_wait,不存在竞争条件。

q265_frame_cond_broadcast,所有等待的线程会同步获取互斥量吗?

pthread_cond_broadcast 唤醒当前在条件变量上等待的所有线程。一次只有一个线程可以锁定一个互斥体,因此这些被唤醒的线程在锁定互斥体时会排队。

或者他们必须竞争以获得互斥锁?

从概念上讲,pthread_cond_wait 必须在返回时锁定互斥锁。这被称为thundering herd problem

Linux 通过将条件变量上的等待者队列移动到互斥体上的等待者队列来解决这个问题,以避免唤醒将立即在互斥体上阻塞的线程。这被称为等待变形

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-07
    • 1970-01-01
    • 1970-01-01
    • 2019-08-08
    • 1970-01-01
    • 1970-01-01
    • 2012-03-18
    相关资源
    最近更新 更多