linux多线程编程之java售票程序的移植

8 篇文章 0 订阅
1 篇文章 0 订阅
 

不多解析了这个,直接贴代码了

开辟4个线程售票啊

#include<stdio.h>
#include<pthread.h>
int tickets=1000;
pthread_mutex_t  mutex;
void *T_fun1()
{
   while(tickets>0)
   {
   pthread_mutex_lock(&mutex);
    printf("Linux thread 1 sales %d ticket\n",tickets);
    tickets--;
   pthread_mutex_unlock(&mutex);
  sleep(1);
   }
}
void *T_fun2()
{
    while(tickets>0)
   {

  pthread_mutex_lock(&mutex);//锁定
 
   printf("Linux thread 2 sales %d ticket\n",tickets);
   tickets--;
  pthread_mutex_unlock(&mutex);
 sleep(1);
   }
 
}
void *T_fun3()
{
    while(tickets>0)
   {

  pthread_mutex_lock(&mutex);//互斥(chi)加锁
 
   printf("Linux thread 3 sales %d ticket\n",tickets);
   tickets--;
  pthread_mutex_unlock(&mutex);//解锁互斥量
 sleep(1);
   }
 
}
void *T_fun4()
{
    while(tickets>0)
   {

  pthread_mutex_lock(&mutex);//互斥(chi)加锁
 
   printf("Linux thread 4 sales %d ticket\n",tickets);
   tickets--;
  pthread_mutex_unlock(&mutex);//解锁互斥量
 sleep(1);
   }
 
}
int main()
{
pthread_t id1;
pthread_t id2;
pthread_t id3;
pthread_t id4;
pthread_mutex_init(&mutex,NULL);
pthread_create(&id1,NULL,T_fun1,NULL);//参数3为线程运行函数起始地址
pthread_create(&id2,NULL,T_fun2,NULL);
pthread_create(&id3,NULL,T_fun3,NULL);
pthread_create(&id4,NULL,T_fun4,NULL);
sleep(100);//主进程休眠时间
printf("main  sleep 100 second end\n");
return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值