多线程售票

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<pthread.h>
#include<unistd.h>
typedef struct SellInfo
{
	int id;//城市序号 
	int num;//票数 
	int hot;//热度 
	double time;//耗时 
	int isOut;//状态 
}sellInfo;
void *sell(void *v);
char *cities[4]={"beijing","shanghai","Guangzhou" , "chengdu"};
int maxTime=500;
int main(){
	int n=4;
	int x=400;
	srand(time(NULL));
	pthread_t th[4]={0};//定义四个线程 
	sellInfo *p[4];//指针数组 
	for(int i=0;i<n;++i){
		p[i]=(struct SellInfo*)malloc(sizeof(struct SellInfo));
		p[i]->id=i;
		p[i]->num=x/n;
		p[i]->hot=rand()%10+1;
		p[i]->time=-1;
		p[i]->isOut=1;
		pthread_create(&th[i],NULL,sell,p[i]);//线程创建 
	}
	for(int i=0;i<n;i++){
		pthread_join(th[i],NULL);//线程等待 
	}
	for(int i=0;i<n;i++){
		printf("%s耗时%lf HOT=%d\n",cities[p[i]->id],p[i]->time,p[i]->hot);
		if(!p[i]->isOut) printf("没有卖完!\n");
		free(p[i]);
	}
	printf("OVER!\n");
	return 0;
}
void *sell(void *v){
	clock_t start,end;//处理器时钟所使用的时间 
	start =clock();
	sellInfo *p=(struct SellInfo*)v;
	int cnt=0;
	while(p->num>0){
		cnt++;
		printf("%s售出第%d张票\n",cities[p->id],cnt); 
		p->num--;
		if(clock()-start>maxTime){
			printf("%s没有卖完\n",cities[p->id]);
			p->isOut=0;
			break;
		}
		int sleepTime=(rand()%10)*1000/p->hot;//微秒(百万分之一秒)
		usleep(sleepTime);//延迟挂起进程
	}
	end =clock();
	p->time=(double)(end-start);
	if(p->isOut) printf("%s sells out!\n\n",cities[p->id]);
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值