下面的例子很简单的使用了 cond 。 使用cond 我们可以比较高效的写出一个 线程池。
#include <pthread.h> #include <unistd.h> #include <stdio.h> pthread_mutex_t mutex; pthread_cond_t cond; int val = 0; void *thread_zero_run(void *arg){ while(1){ pthread_mutex_lock(&mutex); // lock the mutex while(val <= 2){ //condition. use while for double check printf("thread_zero_run --> val:%d, wait for wake up\n", val); pthread_cond_wait(&cond, &mutex);//call pthread_cond_wait } printf("therad_zero_run --> val:%d, zero it and unlock\n", val); val = 0; //do sth pthread_mutex_unlock(&mutex); //unlock the mutex } pthread_exit((void*)0); } void *thread_add_run(void *arg){ while(1){ pthread_mutex_lock(&mutex); //lock the mutex ++val; //do sth pthread_mutex_unlock(&mutex); //unlock the mutex pthread_cond_signal(&cond); //wake up a therad whick is waiting for the cond printf("after add val:%d and wake up one zero thread for check\n", val); sleep(1); } pthread_exit((void*)0); } int main(){ pthread_t t_add, t_zero; pthread_cond_init(&cond, NULL); if(pthread_create(&t_add, NULL, thread_add_run, NULL)){ return 0; } if(pthread_create(&t_zero, NULL, thread_zero_run, NULL)){ return 0; } pthread_join(t_add, NULL); pthread_join(t_zero, NULL); return 0; }
after add val:1 and wake up one zero thread for check thread_zero_run --> val:1, wait for wake up after add val:2 and wake up one zero thread for check thread_zero_run --> val:2, wait for wake up after add val:3 and wake up one zero thread for check therad_zero_run --> val:3, zero it and unlock thread_zero_run --> val:0, wait for wake up after add val:1 and wake up one zero thread for check thread_zero_run --> val:1, wait for wake up after add val:2 and wake up one zero thread for check thread_zero_run --> val:2, wait for wake up after add val:3 and wake up one zero thread for check therad_zero_run --> val:3, zero it and unlock thread_zero_run --> val:0, wait for wake up after add val:1 and wake up one zero thread for check thread_zero_run --> val:1, wait for wake up after add val:2 and wake up one zero thread for check thread_zero_run --> val:2, wait for wake up after add val:3 and wake up one zero thread for check therad_zero_run --> val:3, zero it and unlock thread_zero_run --> val:0, wait for wake up