#include<myhead.h>
phtread_cond_t cond;//定义条件变量
phtread_mutex_t mutex;//定义互斥锁
void *task1(void *arg)//常见生产者线程
{
while(1)
{
sleep(3);
printf("我生产了一辆跑车\n");
//pthread_cond_signal(&cond); //唤醒队列中下一个等待线程
pthread_cond_broadcast(&cond);//唤醒队列中的所有等待线程
}
}
void *task2(void *arg)//创建消费者线程
{
while(1)
{
sleep(1);
phtread_mutex_lock(&mutex);//上锁
pthread_cond_wait(&cond,&mutex);//申请资源
printf("%#ld:我消费一辆跑车\n",pthread_self());
phtread_mutex_unlock(&mutex);//解锁
}
}
void *task3(void *arg)//创建消费者线程
{
while(1)
{
sleep(1);
phtread_mutex_lock(&mutex);
pthread_cond_wait(&cond,&mutex);
printf("%#ld:我消费一辆跑车\n",pthread_self());
phtread_mutex_unlock(&mutex);
}
}
void *task4(void *arg)//创建消费者线程
{
while(1)
{
sleep(1);
phtread_mutex_lock(&mutex);
phtread_cond_wait(&cond,&mutex);
printf("%#ld:我消费一辆跑车\n",pthread_self());
phtread_mutex_unlock(&mutex);
}
}
int main(int argc, const char *argv[])
{
pthread_t tid1,tid2,tid3,tid4;//定义四个线程
if(pthread_create(&tid1,NULL,task1,NULL))
{
perror("create tid1 error");
return -1;
}
if(pthread_create(&tid2,NULL,task2,NULL))
{
perror("creaate tid2 error");
return -1;
}
if(pthread_create(&tid3,NULL,task3,NULL))
{
perror("create tid3 error");
return -1;
}
if(pthread_create(&tid4,NULL,task4,NULL))
{
perror("create tid4 error");
return -1;
}
pthread_cond_init(&cond,NULL);//初始化条件变量
pthread_mutex_init(&mutex,NULL);//初始化锁
printf("tid1=%#lx,tid2=%#lx,tid3=%#lx,tid4=%#lx",\
tid1,tid2,tid3,tid4);//输出四个线程
//回收四个线程的资源
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
pthread_join(tid3,NULL);
pthread_join(tid4,NULL);
pthread_cond_destory(&cond); //释放条件变量
pthread_mutex_destory(&mutex);//释放锁
return 0;
}