c中的多个条件变量

multiple condition variables in c

我正在用 C 开发一个应用程序,其中线程 A 必须等待来自 3 个不同线程的三个事件(如数据接收),即 B, C、D。我可以使用 pthread_cond_waitpthread_cond_signalmutex[= 来实现单个事件19=] 但我想将这个概念扩展到使用单个条件变量和单个互斥锁的多个事件。有人可以帮我解决这个问题吗?

提前致谢。

这真的没有什么棘手的:假设一个事件你在线程 A 中有如下代码:

pthread_mutex_lock(&lock);
while (!event_b_pending)
    pthread_cond_wait(&cond, &lock);

/* Process Event B */

线程 B 中的代码如下:

pthread_mutex_lock(&lock);
event_b_pending = 1;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&lock);

然后对于三个事件,您可以将线程 A 更改为:

pthread_mutex_lock(&lock);
while (!event_b_pending && !event_c_pending && !event_d_pending)
    pthread_cond_wait(&cond, &lock);

if (event_b_pending)
{
    /* Process Event B */
}

if (event_c_pending)
{
    /* Process Event C */
}

if (event_d_pending)
{
    /* Process Event D */
}

线程 C 和 D 像线程 B 一样工作(除了设置适当的标志)。