#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也不见另一个线程被调度执行。
慕森王