我正在尝试实现pthread_cond_wait
2 个线程。我的测试代码试图使用两个线程来执行以下场景:
- 线程 B 等待条件
- 线程 A 打印了五次“Hello”
- 线程 A 向线程 B 发出信号
- 线程 A 等待
- 线程 B 打印“再见”
- 线程 B 向线程 A 发出信号
- 循环开始 (x5)
到目前为止,代码打印了五次“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”编译的代码)