c++ - Pthread查询: Sequence of threads error

标签 c++ c pthreads

#include<pthread.h>
#include<stdio.h>

int num_threads=3;

int state=0;

pthread_cond_t cond;

pthread_mutex_t mutex;

void* threadA(void* args) {

int i;
for(i=0; i<5; i++){ 
    pthread_mutex_lock(&mutex);

        while(state == 1 || state == 2) pthread_cond_wait(&cond,&mutex);

        printf("Thread A\n");
        state = (state+1)%num_threads;
        pthread_cond_signal(&cond);

    pthread_mutex_unlock(&mutex);
}
}

void* threadB(void* args) {

int i;
for(i=0; i<5; i++){ 
    pthread_mutex_lock(&mutex);

        while(state == 0 || state == 2)pthread_cond_wait(&cond,&mutex);

        printf("Thread B\n");
        state = (state+1)%num_threads;
        pthread_cond_signal(&cond);

    pthread_mutex_unlock(&mutex);
}
}

void* threadC(void* args) {

int i;
for(i=0; i<5; i++){ 
    pthread_mutex_lock(&mutex);

        while(state == 1 || state == 0) pthread_cond_wait(&cond,&mutex);

        printf("Thread C\n\n");
        state = (state+1)%num_threads;
        pthread_cond_signal(&cond);

    pthread_mutex_unlock(&mutex);
}
}


int main() {

pthread_t tid[3];

pthread_cond_init(&cond,NULL);
pthread_mutex_init(&mutex,NULL);

pthread_create(&tid[0],NULL,threadA,NULL);
pthread_create(&tid[1],NULL,threadB,NULL);      
pthread_create(&tid[2],NULL,threadC,NULL);

return 0;

问题:使用上面的代码,我想打印 threaA threadB threadC 依次执行 5 次。 但答案是不确定的。而订单 的线程被维护,答案不会被打印 5 次。 请帮忙!!!

最佳答案

正如@mch 在评论中提到的,在允许 main() 函数返回之前,您需要等待线程完成:

pthread_join(tid[0], NULL);
pthread_join(tid[1], NULL);
pthread_join(tid[2], NULL);

现在,将上面的连接添加到 main() 的末尾后,您的程序通常会挂起。发生这种情况是因为 pthread_cond_signal() 没有唤醒所有等待该条件变量的线程。如果唤醒了错误的线程(例如,threadC 发出条件信号,但收到通知的线程不是 threadA),那么所有线程都将等待该条件,并且不会有人发出该条件信号。

要解决此问题,您需要确保每次都唤醒所有线程,并让每个线程自行决定是否轮到它(通过 while(state...) pthread_cond_wait(. ..);)。为此,您可以将对 pthread_cond_signal() 的调用替换为对 pthread_cond_broadcast() 的调用,这会取消阻塞当前在该条件下阻塞的所有 线程.

关于c++ - Pthread查询: Sequence of threads error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30459351/

相关文章:

gdb - 如何将 gdb 调试一次限制为一个线程

c++ - 如何在 C++ 中创建动态分配的二维结构数组?

c++ - 截屏到 Direct2D 兼容位图

C简单程序

c - 调用 pthread_spin_destroy() 时,到底释放了什么 "resources"?

c++ - 基于 pthread 的多功能多线程实用程序库

c++ - 使用 memcpy 或对结构中的数组赋值的访问冲突

c++ - 为什么c++中的引用传递用functionName(dataType& variableName)来表示?

c++ - 32 位代码在 64 位 linux 机器上运行

c - 浮点模运算