下面的程序工作正常。但我的疑问是一开始两个线程(printEven和printOdd)都在等待条件变量(语句pthread_cond_wait(&cond,&mutex);)的信号,那么printOdd如何能够进一步进行,即使printEven当时不能如此信号。
我将把它在一个简单的方式如何数字1是得到打印?任何人都可以请帮助我字面上坚持与此很长一段时间。
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
pthread_t tid[2];
pthread_mutex_t mutex;
pthread_cond_t cond;
int count = 1; // Shared variable to keep track of the current number to be printed
void* printEven(void* arg) {
while (count <= 10) {
pthread_mutex_lock(&mutex);
while (count % 2 != 0) {
printf("waiting for cv signal\n");
pthread_cond_wait(&cond, &mutex);
}
printf("Even: %d\n", count++);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
void* printOdd(void* arg) {
while (count <= 10) {
pthread_mutex_lock(&mutex);
while (count % 2 != 1) {
pthread_cond_wait(&cond, &mutex);
}
printf("Odd: %d\n", count++);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
int main() {
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
pthread_create(&tid[1], NULL, printOdd, NULL);
sleep(10);
printf("creating even thread\n ");
pthread_create(&tid[0], NULL, printEven, NULL);
pthread_join(tid[0], NULL);
pthread_join(tid[1], NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}
字符串
1条答案
按热度按时间lymnna711#
数字1被打印出来是因为你正在以正确的方式使用
pthread_cond_wait
。当printOdd
第一次被调用时,count
等于1,所以count%2
等于1,所以函数 * 不 * 调用pthread_cond_wait。通常,使用pthread_cond_wait的正确方法是,
字符串
而且,锁定互斥锁的全部意义在于,除非互斥锁被锁定,否则任何线程都不应改变条件是否满足。