gpt4 book ai didi

c++ - 关于 pthread_cond_wait?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:08:07 26 4
gpt4 key购买 nike

我有以下代码:

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 );
}

最佳答案

The question is: Is it valid that several threads call the q265_frame_cond_wait synchronously

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

q265_frame_cond_broadcast, will all the waiting thread get the mutex synchronously?

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

Or they must compete to get the mutex?

概念上是的,pthread_cond_wait 必须在返回时锁定互斥体。这被称为 thundering herd problem .

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

关于c++ - 关于 pthread_cond_wait?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39252605/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com