两个线程实现同步
#include <myhead.h>
//定义条件变量
pthread_cond_t cond;
//定义互斥锁
pthread_mutex_t mutex;
//生产者
void *task1(void *arg)
{int num = 3;while(num--){sleep(1);printf("做了一顿饭\n");//唤醒等待队列中的所有线程pthread_cond_signal(&cond);}//退出线程pthread_exit(NULL);
}
//定义消费者线程
void *task2(void *arg)
{//获取锁资源pthread_mutex_lock(&mutex);//等待生产者线程的资源 pthread_cond_wait(&cond, &mutex);printf("吃了一顿饭\n");//释放锁资源pthread_mutex_unlock(&mutex);//退出线程pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{//定义两个线程号pthread_t tid1, tid2,tid3,tid4;//初始化条件变量pthread_cond_init(&cond, NULL);//初始化互斥锁pthread_mutex_init(&mutex, NULL);//创建生产者线程if(pthread_create(&tid1, NULL, task1, NULL) != 0){printf("tid1 create error\n");return -1;}//创建消费者线程if(pthread_create(&tid2, NULL, task2, NULL) != 0){printf("tid2 create error\n");return -1;}if(pthread_create(&tid3, NULL, task2, NULL) != 0){printf("tid3 create error\n");return -1;}if(pthread_create(&tid4, NULL, task2, NULL) != 0){printf("tid4 create error\n");return -1;}//回收线程资源pthread_join(tid1 , NULL);pthread_join(tid2 , NULL);//销毁条件变量pthread_cond_destroy(&cond);//销毁互斥锁pthread_mutex_destroy(&mutex);return 0;
}
演示