#include <unistd.h>
#include <pthread.h>
#include <stdio.h>
pthread_mutex_t Poll_Work; //互斥
pthread_cond_t Poll_Full; //条件
void* thread0(void *param)
{
while(*(int*)param < 100 && *(int*)param >= 0){
pthread_mutex_lock(&Poll_Work);
(*(int*)param) += 5;
printf("Thread0: %d\n", *(int*)param);
pthread_mutex_unlock(&Poll_Work);
sleep(2);
}
pthread_cond_signal(&Poll_Full);
return NULL;
}
void* thread1(void *param)
{
while(*(int*)param < 100 ){
pthread_mutex_lock(&Poll_Work);
(*(int*)param) -= 5;
printf("Thread1: %d\n", *(int*)param);
pthread_mutex_unlock(&Poll_Work);
sleep(2);
}
pthread_cond_signal(&Poll_Full);
return NULL;
}
void* thread2(void *param)
{
pthread_mutex_lock(&Poll_Work);
while(*(int*)param < 100)
pthread_cond_wait(&Poll_Full, &Poll_Work);
printf("Thread2: Poll Is Full!!\n");
pthread_mutex_unlock(&Poll_Work);
return NULL;
}
int main()
{
int sum = 0; //水深 满为100米 初始化 池里没有水
int i;
pthread_mutex_init(&Poll_Work, NULL);
pthread_cond_init(&Poll_Full, NULL);
pthread_t ths[3];
pthread_create(&ths[0], NULL, thread0, (void*)&sum);
pthread_create(&ths[1], NULL, thread1, (void*)&sum);
pthread_create(&ths[2], NULL, thread2, (void*)&sum);
for(i = 0; i < 3; ++ i){
pthread_join(ths[i], NULL);
}
printf("Play End!\n");
}
程序大概意思 一个可以装100水的pool 两个线程 一个不断加5 一个不断减3 第三个线程用于输出 当满的时候 输出Full 可是运行程序后 发现总是只有一个线程在运行 另一个完全没反应。 加了sleep也不见另一个线程被调度执行。
为什么呢?
sleep位置改了也不行~ 如上改在解锁后面还是不行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
因为你的sleep放错了地方,应该是放在 pthread_mutex_unlock 后面。
另外,不建议使用sleep,建议使用pthread_yield来放弃cpu。
然后你就会发现你的代码逻辑有些问题,比如说sum < 0了,thread1还在继续运行。
问题已经解决,如上面这位兄台说的 sleep的位置的问题 上面之所以改完也没输出跟我虚拟机的配置有关撒~