编写多线程火车售票模拟程序

用c语言编写一个基于多线程的火车售票模拟程序。假如火车站有15张票要售出,现有2个售票点售票,其中售票点1每秒钟售出一篇火车票,售票点2每两秒钟售出一张火车票,用2个线程模拟2个售票情况。编译运行程序输入如下信息(输出的先后顺序不一定需要完全一样),其中W1代表售票点1,W2代表售票点2。

源代码:

(注意!!)sleep(1);//这里,如果用sleep(1.0)就只能运行两个就停下了,,,(找错半天才发现是这里的原因,,,,好坑(~ _ ~),,,)

#include  <stdio.h>
#include  <stdlib.h>
#include  <pthread.h>
#include  <ctype.h>

int total_words;
void *sub_count(int);
pthread_mutex_t counter_lock=PTHREAD_MUTEX_INITIALIZER;

main(int ac, char *av[])
{
	pthread_t t1, t2;		// two threads 

	total_words =15;

	pthread_create(&t1, NULL, sub_count, (int) 1);
	pthread_create(&t2, NULL, sub_count, (int) 2);
	pthread_join(t1, NULL);
	pthread_join(t2, NULL);
	
}

void *sub_count(int x)
{
	int sum1=0,sum2=0;
	int temp; 
	while(total_words>0)
	{
		if(x==1)
		{
        		pthread_mutex_lock(&counter_lock);
        		temp = total_words;
        		temp--;
	        	total_words=temp;
			printf("w1:%5d tickets are left\n",total_words);
			sum1++;
			fflush(stdout);
        		pthread_mutex_unlock(&counter_lock);
			sleep(1);//这里,如果用sleep(1.0)就只能运行两个就停下了
		}
		else if(x==2)
		{
			pthread_mutex_lock(&counter_lock);
        		temp = total_words;
        		temp--;
			total_words=temp;
			printf("w2:%5d tickets are left\n",total_words);
			sum2++;		
			fflush(stdout);
        		pthread_mutex_unlock(&counter_lock);
			sleep(2);	
		}
	}
	if(x==2)
		printf("w2:%5d tickets were sold from window 2\n",sum2);
	if(x==1)
		printf("w1:%5d tickets were sold from window 1\n",sum1);
	return NULL;
}

代码编译命令:

gcc sale.c -o sale -lpthread

运行结果截图:

 

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值