Pthread查询:线程顺序错误

Pthread query: Sequence of threads error

本文关键字:顺序 错误 线程 查询 Pthread      更新时间:2023-10-16
#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 An");
        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 Bn");
        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 Cnn");
        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;

}

问题:用上面的代码,我想打印threada 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()不会唤醒等待该条件变量的所有线程。如果错误的线程被唤醒(例如,线程c发出条件信号,但被通知的线程不是线程a),那么所有线程将等待条件,并且没有人通知该条件。

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