本文主要是介绍编写多线程火车售票模拟程序,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
用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
运行结果截图:
这篇关于编写多线程火车售票模拟程序的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!