c - c中的多个条件变量

标签 c pthreads

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

提前致谢。

最佳答案

这确实没有什么棘手的:假设对于一个事件,您在线程 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 类似(除了设置适当的标志)。

关于c - c中的多个条件变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36963458/

相关文章:

c - 函数声明错误

c - 迭代字符串输入

c - 错误: No such file or directory on Xcode

c++ - 如何中断无限的 sigtimedwait?

c - 关于 PThread 和 PThread 屏障

c - 使用 fscanf 读取 ASCII 码文件

c++ - 混合 C++11 std::thread 和 C 系统线程(即 pthreads)

c - 如何在 Linux 上使线程超时?

objective-c - 加载 dylib 时垃圾收集工作队列崩溃

c++ - 如何访问静态 void* 函数中的私有(private)成员