Linux下pthread_cond_wait()多线程同步实例

来源:互联网 发布:山东塑胶跑道标准数据 编辑:程序博客网 时间:2024/06/15 07:17

使用pthread_cond_wait()函数进行多线程同步。
一般与pthread_mutex_t 互斥锁一起使用。
下面是简单demo,主线程每2秒让子线程运行5次。

#include <stdint.h>#include <semaphore.h>#include <stdio.h>#include <stdlib.h>#include <pthread.h>#include <unistd.h>#include <string.h>pthread_mutex_t lock;pthread_cond_t cond;int num = 0;void *func(void *arg){  while(1)  {    while(num <= 0)    {      pthread_mutex_lock(&lock);      printf("wait do something....\n");      pthread_cond_wait(&cond,&lock);      pthread_mutex_unlock(&lock);    }    //do something....    printf("hello world...\n");    pthread_mutex_lock(&lock);    num --;    pthread_mutex_unlock(&lock);    usleep(100000);  }}int main(){  pthread_t ps;  //初始化  pthread_mutex_init(&lock,NULL);    pthread_cond_init(&cond, NULL);  //创建线程  pthread_create(&ps,NULL,func,NULL);  while(1)  {    //修改全局变量值,使func线程解除阻塞等待    pthread_mutex_lock(&lock);    num = 5;    pthread_cond_signal(&cond);    pthread_mutex_unlock(&lock);    sleep(2);  }  return 0;}
0 0