c - 多个生产者中的 posix 线程互斥和条件变量使用

标签 c pthreads mutex wait

我试图在多线程生产和单线程消费的情况下找出互斥和条件变量的执行。

这里是示例代码:

#include<stdio.h>
#include<pthread.h>
int done = 0;
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t c = PTHREAD_COND_INITIALIZER;
void *thr2(void *arg) {
     pthread_t self;
     self=pthread_self();
     pthread_mutex_lock(&m);
     done = 1;
     pthread_cond_signal(&c);
     pthread_mutex_unlock(&m);
     return NULL;
}
void *thr1(void *arg) {
     pthread_t self;
     self=pthread_self();
     pthread_mutex_lock(&m);
     while (done == 0)
     {
          pthread_cond_wait(&c, &m);
     }
     pthread_mutex_unlock(&m);
}
int main(int argc, char *argv[]) {
     pthread_t p,q,r;
     pthread_create(&q, NULL, thr1, NULL);
     sleep(2);
     pthread_create(&p, NULL, thr2, NULL);
     pthread_create(&r, NULL, thr2, NULL);
     pthread_join(p,NULL);
     pthread_join(q,NULL);
     pthread_join(r,NULL);
     return 0;
}

在此代码中,我希望线程 1 等待条件变量完成。因此,线程 2 或线程 3 中的任何一个启动并获得互斥锁和更改为 1 时。它必须向正在等待的线程 1 发出信号,线程 1 将开始执行。

但是,我看到即使 thread1 正在等待条件变量 done=0 并且在来自 thread2 的信号之后,我为 thread2 方法创建的另一个线程获得了互斥量。

我想知道我对输出的期望是否有问题。我正在尝试在类似情况下实现阻塞队列,其中可以有多个生产者和一个消费者。

谢谢, 普瓦南。

最佳答案

你的期望是错误的。线程 1 将最终唤醒并获得互斥锁,因为它已收到信号,但不能保证线程 3 不会先到达那里。

如果您不希望您的生产者线程在队列已满时“生产”(这里,您的队列长度为 1),那么您也需要让它们等待 - 您可以使用第二个条件变量那:

int done = 0;
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t c_done = PTHREAD_COND_INITIALIZER;
pthread_cond_t c_undone = PTHREAD_COND_INITIALIZER;

void *thr2(void *arg)
{
     pthread_mutex_lock(&m);
     /* wait for done to be zero */
     while (done != 0)
         pthread_cond_wait(&c_undone, &m);
     done = 1;
     pthread_cond_signal(&c_done);
     pthread_mutex_unlock(&m);
     return NULL;
}

void *thr1(void *arg)
{
     pthread_mutex_lock(&m);
     while (done == 0)
     {
          pthread_cond_wait(&c_done, &m);
     }
     done = 0;
     pthread_cond_signal(&c_undone);
     pthread_mutex_unlock(&m);
}

关于c - 多个生产者中的 posix 线程互斥和条件变量使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31089053/

相关文章:

你能在 C 中定义一个返回 bool 的函数吗?

c++ - Pthreads 类似信号的暂停?

c++ - 在 Linux 上编写多线程 TCP 服务器

ruby-on-rails-3 - 错误线程错误: Attempt to unlock a mutex which is locked by another thread

c++ - 互斥锁操作是否应该因锁定两次而引发 system_error?

objective-c - 在串口上用read()操作取消线程

c - 在c中格式说明符中使用 `+`

c++ - 如何分析基于 C++ STL 的程序以检测 STL 互斥锁?

c - 对循环中的信号进行非阻塞检查

c++ - pthread_sigmask :unusual behavior