两个线程实现同步代码示例
#include <myhead.h>
//1、定义条件变量
pthread_cond_t cond;
//11、定义互斥锁
pthread_mutex_t mutex;
//定义生产者线程
void *task1(void *arg)
{
sleep(1);
printf("%#lx:生产了两辆汽车\n", pthread_self());
//3、唤醒等待队列中的所有线程
pthread_cond_broadcast(&cond);
//退出线程
pthread_exit(NULL);
}
//定义消费者线程
void *task2(void *arg)
{
//33、获取锁资源
pthread_mutex_lock(&mutex);
//4、等待生产者线程的资源
pthread_cond_wait(&cond, &mutex);
printf("%#lx:购买了一辆汽车\n", pthread_self());
//44、释放锁资源
pthread_mutex_unlock(&mutex);
//退出线程
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
//定义两个线程号
pthread_t tid1, tid2, tid3, tid4, tid5;
//2、初始化条件变量
pthread_cond_init(&cond, NULL);
//22、初始化互斥锁
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;
}
printf("tid1 = %#lx, tid2 = %#lx, tid3 = %#lx\n",tid1, tid2, tid3);
//回收线程资源
pthread_join(tid1 , NULL);
pthread_join(tid2 , NULL);
pthread_join(tid3, NULL);
//5、销毁条件变量
pthread_cond_destroy(&cond);
//55、销毁互斥锁
pthread_mutex_destroy(&mutex);
return 0;
}