/* 使用多线程实现卖票的案例
有三个窗口,一共是100张票
*/
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
int tickets =1000;
pthread_mutex_t mutex;
void* sellticket(void* arg){
while(1){
//上锁
pthread_mutex_lock(&mutex);
if(tickets>0){
usleep(3000);
printf("%ld 正在卖第%d张门票\n",pthread_self(),tickets);
tickets--;
}else{
//解锁
pthread_mutex_unlock(&mutex);
break;
}
//解锁
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main(){
//初始化锁
pthread_mutex_init(&mutex,NULL);
pthread_t tid1,tid2,tid3;
pthread_create(&tid1,NULL,sellticket,NULL);
pthread_create(&tid2,NULL,sellticket,NULL);
pthread_create(&tid3,NULL,sellticket,NULL);
//回收子线程的资源,阻塞
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
pthread_join(tid3,NULL);
//摧毁锁
pthread_mutex_destroy(&mutex);
pthread_exit(NULL);
return 0;
}
线程同步实例
于 2023-03-11 10:35:19 首次发布