int tickets=1000; pthread_mutex_t mutex;
void* sellticket(void*arg){ //加锁 while(1){ pthread_mutex_lock(&mutex); if(tickets>0){ usleep(6000); 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); //创建3个子线程 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_exit(NULL);//退出主线程
//设置线程分离 //pthread_detach(tid1); //pthread_detach(tid2); //pthread_detach(tid3); pthread_mutex_destroy(&mutex); return 0; }