#include <stdio.h>
#include <time.h>
#include <semaphore.h>
int ticket = 100;
sem_t sem;
void *sellticket(void *v)
{
long num = (long)v;
srand((unsigned int)time(NULL));
while (1)
{
usleep(100000*(rand()%10+1));
sem_wait(&sem); // p操作
if (0 == ticket)
{
printf ("票卖完了\n");
sem_post(&sem); // v操作
break;
}
printf ("%ld号窗口卖了一张票,座位号:%d\n",num, ticket);
ticket -= 1;
sem_post(&sem); // v操作
}
}
int main(int argc, char **argv)
{
int i;
for(i = 0; i < 4; i++)
{
pthread_t thread;
pthread_create(&thread, NULL, sellticket, (void*)(i+1));
pthread_detach(thread);
}
sem_init(&sem, 0, 1);
pthread_exit(NULL);
return 0;
}
多线程卖票系统
猜你喜欢
转载自blog.csdn.net/weixin_43664746/article/details/85275587
今日推荐
周排行