不多解析了这个,直接贴Linux多线程编程之Java售票程序的移植代码.
开辟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;
}