Pthread查询:线程序列错误

时间:2015-05-26 13:01:35

标签: 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次。           请帮忙!!!

1 个答案:

答案 0 :(得分:3)

正如注释中提到的@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()的来电,这会取消阻止此条件下当前阻止的所有主题。