#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]);
}
01-10
03-01
188