概述
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
//#include <unistd.h>
//#include <errno.h>
#include <time.h>
pthread_mutex_t mutex;
pthread_cond_t cond1;
pthread_cond_t cond2;
pthread_cond_t cond3;
int ticket = 10;
void *sell_ticket1(void)
{
while(1)
{
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond1,&mutex);
if(ticket > 0)
{
printf("sell ticket1--> chool ticket:%dn",ticket--);
//sleep(1);
pthread_mutex_unlock(&mutex);
}
else
{
pthread_mutex_unlock(&mutex);
break;
}
}
return NULL;
}
void *sell_ticket2(void)
{
while(1)
{
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond2,&mutex);
if(ticket > 0)
{
//sleep(1);
printf("sell ticket2--> chool ticket:%dn",ticket--);
//sleep(1);
pthread_mutex_unlock(&mutex);
}
else
{
pthread_mutex_unlock(&mutex);
break;
}
}
}
void *sell_ticket3(void)
{
while(1)
{
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond3,&mutex);
if(ticket > 0)
{
//sleep(1);
printf("sell ticket3--> chool ticket:%dn",ticket--);
//sleep(1);
pthread_mutex_unlock(&mutex);
}
else
{
pthread_mutex_unlock(&mutex);
break;
}
}
return NULL;
}
int main()
{
int i=0,flog=0,ret=0;
pthread_t id1,id2,id3;
int old_ticket = ticket;
srand(time(NULL));
pthread_mutex_init(&mutex,NULL);
pthread_cond_init(&cond1,NULL);
pthread_cond_init(&cond2,NULL);
pthread_cond_init(&cond3,NULL);
ret = pthread_create(&id1, NULL, (void*)sell_ticket1, NULL);
if(ret == -1)
{
printf("create_thread1 error!n");
exit(-1);
}
ret = pthread_create(&id2, NULL, (void*)sell_ticket2, NULL);
if(ret == -1)
{
printf("create_thread2 error!n");
exit(-1);
}
ret = pthread_create(&id3, NULL, (void*)sell_ticket3, NULL);
if(ret == -1)
{
printf("create_thread3 error!n");
exit(-1);
}
sleep(1);
for(i =0; i< old_ticket; i++)
{
flog = rand() % 3;
//printf("%dn",flog);
switch(flog)
{
case 0: pthread_cond_signal(&cond1);break;
case 1: pthread_cond_signal(&cond2);break;
case 2: pthread_cond_signal(&cond3);break;
}
sleep(1);
}
pthread_cond_signal(&cond1);
sleep(1);
pthread_cond_signal(&cond2);
sleep(1);
pthread_cond_signal(&cond3);
sleep(1);
ret = pthread_join(id1, NULL);
if(ret == -1)
{
printf("join_thread1 error!n");
exit(-1);
}
printf("id1 exit!n");
ret = pthread_join(id2, NULL);
if(ret == -1)
{
printf("join_thread2 error!n");
exit(-1);
}
printf("id2 exit!n");
ret = pthread_join(id3, NULL);
if(ret == -1)
{
printf("join_thread3 error!n");
exit(-1);
}
printf("id3 exit!n");
return 0;
}
最后
以上就是优美草丛为你收集整理的简单的,通过线程实现三人卖票系统。的全部内容,希望文章能够帮你解决简单的,通过线程实现三人卖票系统。所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复