概述
线程1:
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
int Ticket = 200;
pthread_mutex_t mutex; //定义互斥锁
void delay()
{
int x = 10000, y;
while (x > 0)
{
y = 10000;
while (y > 0)
{
y--;
}
x--;
}
}
void *SaleTicket(void *arg)
{
int cur_ticket;
while (1)
{
pthread_mutex_lock(&mutex); //访问数据前加锁
cur_ticket = Ticket;
if (cur_ticket <= 0)
{
pthread_mutex_unlock(&mutex);
break;
}
printf("%lu get ticket %dn", pthread_self(), cur_ticket);
cur_ticket--;
//usleep(10000);
delay();
Ticket = cur_ticket;
pthread_mutex_unlock(&mutex); //访问数据结束,解锁
}
}
int main()
{
pthread_t tid[SIZE] = {0};
int i, ret;
pthread_mutex_init(&mutex, NULL); //初始化互斥锁
for (i = 0; i < SIZE; i++)
{
ret = pthread_create(&tid[i], NULL, SaleTicket, NULL);
if (ret != 0)
{
perror("pthread_create");
}
}
for (i = 0; i < SIZE; i++)
{
void *status;
pthread_join(tid[i], &status);
}
pthread_mutex_destroy(&mutex);
return 0;
}
线程2:
#include <stdio.h>
#include <pthread.h>
int Ticket = 100;
pthread_mutex_t mutex;
pthread_cond_t cond; //条件变量
void delay()
{
int x = 5000, y;
while (x > 0)
{
y = 10000;
while (y > 0)
{
y--;
}
x--;
}
}
void *SaleTicketA(void *arg)
{
int cur_ticket;
while (1)
{
pthread_mutex_lock(&mutex);
cur_ticket = Ticket;
if (cur_ticket <= 0)
{
pthread_mutex_unlock(&mutex);
break;
}
if (cur_ticket == 50)
{
pthread_cond_signal(&cond); //唤醒线程B
}
printf("A get ticket %dn", cur_ticket);
cur_ticket--;
Ticket = cur_ticket;
pthread_mutex_unlock(&mutex);
delay();
}
}
void *SaleTicketB(void *arg)
{
int cur_ticket;
while (1)
{
pthread_mutex_lock(&mutex);
cur_ticket = Ticket;
if (cur_ticket <= 0)
{
pthread_mutex_unlock(&mutex);
break;
}
if (cur_ticket > 50)
{
pthread_cond_wait(&cond, &mutex); //线程挂起 同时解锁
cur_ticket = Ticket;
}
printf("B get ticket %dn", cur_ticket);
cur_ticket--;
Ticket = cur_ticket;
pthread_mutex_unlock(&mutex);
delay();
}
}
int main()
{
int ret;
pthread_t tid[2] = {0};
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
ret = pthread_create(&tid[0], NULL, SaleTicketA, NULL);
if (ret != 0)
{
perror("pthread_create");
}
ret = pthread_create(&tid[1], NULL, SaleTicketB, NULL);
if (ret != 0)
{
perror("pthread_create");
}
void *status;
pthread_join(tid[0], &status);
pthread_join(tid[1], &status);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}
最后
以上就是落寞镜子为你收集整理的多线程模拟售票的全部内容,希望文章能够帮你解决多线程模拟售票所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复