多线程同步|多线程同步 顺序打印数字 线程条件变量

先把条件变量函数甩出来,

//等待条件 int pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restric mutex); 1:把调用线程放到所等待条件的线程列表上 2:对传进来已经加过锁的互斥量解锁 3:线程进入休眠状态等待被唤醒 注:1、2步为原子操作//通知条件 int pthread_cond_signal(pthread_cond_t *cond); int pthread_cond_broadcast(pthread_cond_t * cond);

1:通知指定条件已经满足 2:等待线程重新锁定互斥锁 3:等待线程需要重新测试条件是否满足



【多线程同步|多线程同步 顺序打印数字 线程条件变量】


#include #include #include using namespace std; pthread_mutex_t g_mutex; pthread_cond_tg_cond; static int num = 0; void* thread1(void* id); void* thread2(void* id); int main(int argc,char* argv[]) { pthread_mutex_init(&g_mutex,NULL); pthread_cond_init(&g_cond,NULL); pthread_t id[2]; pthread_create(&id[0],NULL,thread1,NULL); pthread_create(&id[1],NULL,thread2,NULL); pthread_join(id[0],NULL); pthread_join(id[1],NULL); pthread_cond_destroy(&g_cond); pthread_mutex_destroy(&g_mutex); int c; while((c =getchar()) != 'c') { sleep(1); } cout<< "exit process from main func" << endl; return 0; }void* thread1(void* id) { while(1) { pthread_mutex_lock(&g_mutex); if(num % 2 == 1) { //enter wait will unlock resource and block current thread. //broadcast will active wait func pthread_cond_wait(&g_cond,&g_mutex); //end wait will lock resource } cout<< "thread 1 : " << num << endl; ++num; if(num > 10000) { pthread_cond_broadcast(&g_cond); pthread_mutex_unlock(&g_mutex); pthread_exit(0); } pthread_cond_broadcast(&g_cond); pthread_mutex_unlock(&g_mutex); } }void* thread2(void* id) { while(1) { pthread_mutex_lock(&g_mutex); if(num % 2 == 0) { pthread_cond_wait(&g_cond,&g_mutex); }if(num > 10000) { pthread_mutex_unlock(&g_mutex); pthread_exit(0); }cout<< "thread 2 : " << num << endl; ++num; pthread_cond_broadcast(&g_cond); pthread_mutex_unlock(&g_mutex); } }



    推荐阅读