利用线程原理模拟火车售票系统:
创建4个线程,其中3个实现售票功能,1个实现退票功能。其中3个售票线程设定每隔一定时间售出一张票,退票线程定时退回一张票。初始车票数量自行设定,输出显示信息根据情况自行拟定。
#include<stdio.h>#include<pthread.h> #include<stdlib.h>#include<unistd.h>#include<time.h>#include<sys/time.h>int tickets=150;//定义售票数pthread_mutex_t lock;// 定义锁//获取系统当前时间int getSystemTime() {time_t timer; struct tm t_tm; time(&timer); localtime_r(&timer, &t_tm); printf("时间: %4d/%02d/%02d %02d:%02d:%02d\r\n", t_tm.tm_year+1900, t_tm.tm_mon+1, t_tm.tm_mday, t_tm.tm_hour, t_tm.tm_min, t_tm.tm_sec); return 0; } //余票不多时进行提醒void Noticeprint(){pthread_mutex_lock(&lock);if(tickets<=10&&tickets>0){printf("票即将售空!剩余%d张\n\n",tickets);}else if(tickets==0){printf("票已售空!\n\n");}pthread_mutex_unlock(&lock);} //购票void *GetTickets(void *args){while(1){Noticeprint(); pthread_mutex_lock(&lock);// 上锁 int ticket=rand()%(10-1+1)+1;//售票数值为随机数if(tickets>0&&ticket<=tickets){getSystemTime();//显示售票时间printf("%s正在为您服务!\n",(char*)args);printf("客户:买%d张车票\n",ticket);printf("窗口:售出%d张车票,剩余%d张\n\n",ticket,tickets-=ticket);pthread_mutex_unlock(&lock);// 解锁 sleep(2); } else {pthread_mutex_unlock(&lock);// 解锁break; } } } //退票void *Refund(void *args){while(1){pthread_mutex_lock(&lock);// 上锁 int ticket=rand()%(10-1+1)+1;if(tickets>0&&(ticket+tickets)<=150) {sleep(5);getSystemTime();printf("%s正在为您服务!\n",(char*)args);printf("客户:退%d张车票\n",ticket);printf("窗口:退回%d张车票,剩余%d张\n\n",ticket,tickets+=ticket);//tickets=tickets-ticket;pthread_mutex_unlock(&lock);// 解锁 } else {pthread_mutex_unlock(&lock); break; } } } int main() {pthread_t t1,t2,t3,t4;//存放线程标识符pthread_mutex_init(&lock,NULL);// 初始化锁 printf("开始售票,现有福州->厦门 150张\n\n"); //创建4个子线程 pthread_create(&t1,NULL,GetTickets,"窗口1");sleep(1); pthread_create(&t2,NULL,GetTickets,"窗口2");sleep(1); pthread_create(&t3,NULL,GetTickets,"窗口3");sleep(1); pthread_create(&t4,NULL,Refund,"窗口4");sleep(1);//等待线程结束 pthread_join(t1,NULL); pthread_join(t2,NULL); pthread_join(t3,NULL); pthread_join(t4,NULL); pthread_mutex_destroy(&lock);// 释放锁}
运行结果:
售票:
退票:
余票不多时进行提醒:
售空退出: