我正在尝试实现pthread_cond_wait2个线程。我的测试代码试图使用两个线程来执行以下方案:
pthread_cond_wait
到目前为止,代码将打印“ Hello”五次,然后卡住。从我看过的示例中,我似乎走对了,“锁定互斥锁,等待,由其他线程发出信号,解锁互斥锁,执行操作,循环”
测试代码:
//Import #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <unistd.h> //global variables pthread_cond_t condA = PTHREAD_COND_INITIALIZER; pthread_cond_t condB = PTHREAD_COND_INITIALIZER; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void *threadA() { int i = 0, rValue, loopNum; while(i<5) { //unlock mutex rValue = pthread_mutex_unlock(&mutex); //do stuff for(loopNum = 1; loopNum <= 5; loopNum++) printf("Hello %d\n", loopNum); //signal condition of thread b rValue = pthread_cond_signal(&condB); //lock mutex rValue = pthread_mutex_lock(&mutex); //wait for turn while( pthread_cond_wait(&condA, &mutex) != 0 ) i++; } } void *threadB() { int n = 0, rValue; while(n<5) { //lock mutex rValue = pthread_mutex_lock(&mutex); //wait for turn while( pthread_cond_wait(&condB, &mutex) != 0 ) //unlock mutex rValue = pthread_mutex_unlock(&mutex); //do stuff printf("Goodbye"); //signal condition a rValue = pthread_cond_signal(&condA); n++; } } int main(int argc, char *argv[]) { //create our threads pthread_t a, b; pthread_create(&a, NULL, threadA, NULL); pthread_create(&b, NULL, threadB, NULL); pthread_join(a, NULL); pthread_join(b,NULL); }
朝着正确方向的指针将不胜感激,谢谢!(在Linux上使用“ gcc timeTest.c -o timeTest -lpthread”编译的代码)
你有两个问题。首先是您没有while()正确使用循环-例如,在这里:
while()
//wait for turn while( pthread_cond_wait(&condA, &mutex) != 0 ) i++;
在体内while循环是声明i++-这将执行pthread_cond_wait()并i++直到pthread_cond_wait()返回一个错误,所以这基本上是一个死循环。
while
i++
pthread_cond_wait()
第二个问题是您不能单独使用pthreads条件变量- 它需要与一些实际的共享状态配对(最简单的说,此共享状态可能只是受互斥锁保护的标志变量)。该pthread_cond_wait()函数用于等待共享状态达到某个值,并且pthread_cond_signal()当线程更改共享状态时使用该函数。重新编写示例以使用这样的变量:
pthread_cond_signal()
//global variables /* STATE_A = THREAD A runs next, STATE_B = THREAD B runs next */ enum { STATE_A, STATE_B } state = STATE_A; pthread_cond_t condA = PTHREAD_COND_INITIALIZER; pthread_cond_t condB = PTHREAD_COND_INITIALIZER; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void *threadA() { int i = 0, rValue, loopNum; while(i<5) { /* Wait for state A */ pthread_mutex_lock(&mutex); while (state != STATE_A) pthread_cond_wait(&condA, &mutex); pthread_mutex_unlock(&mutex); //do stuff for(loopNum = 1; loopNum <= 5; loopNum++) printf("Hello %d\n", loopNum); /* Set state to B and wake up thread B */ pthread_mutex_lock(&mutex); state = STATE_B; pthread_cond_signal(&condB); pthread_mutex_unlock(&mutex); i++; } return 0; } void *threadB() { int n = 0, rValue; while(n<5) { /* Wait for state B */ pthread_mutex_lock(&mutex); while (state != STATE_B) pthread_cond_wait(&condB, &mutex); pthread_mutex_unlock(&mutex); //do stuff printf("Goodbye\n"); /* Set state to A and wake up thread A */ pthread_mutex_lock(&mutex); state = STATE_A; pthread_cond_signal(&condA); pthread_mutex_unlock(&mutex); n++; } return 0; }
需要注意的是使用两个条件变量的condA和condB不必要在这里-代码将是一样,如果正确使用的条件只有一个变量,而不是。
condA
condB