Linux多线程 | 火车站窗口卖票
描述
火车站有3个窗口,去卖100张车票,卖完即停止
思路
典型的多线程编程问题。首先需要三个线程同时去卖票,要保证线程安全,就要使用互斥锁进行保护,防止出现卖出负数的情况 1.开启三个线程 2.使用互斥锁保证线程安全 3.车票为0停止卖票
代码实现
int tickets = 100; pthread_mutex_t mutex; void *buyTicket(void *arg) { while(tickets>0) { pthread_mutex_lock(&mutex); printf("%p窗口卖出一张票%d ",pthread_self(),tickets); tickets--; pthread_mutex_unlock(&mutex); } return NULL; } int main() { pthread_t tid[3]; int ret; pthread_mutex_init(&mutex, NULL); for (int i = 0; i < 3; ++i) { ret = pthread_create(&tid[i], NULL, buyTicket, NULL); if (ret == -1) { printf("create thread error "); return -1; } } for (int i = 0; i < 3; ++i) { pthread_join(tid[i], NULL); } pthread_mutex_destroy(&mutex); }
可以看到只有一个窗口卖出了所有的票,其他两个窗口没有卖出
原因:在卖票函数中,当完成了卖票,进行解锁,此时该线程所分配的cpu时间片还没有完,于是又继续循环上去加锁卖票,以此往复导致只有一个线程卖票,其他线程被卡在获取锁加锁的环节
优化:解锁后增加一个睡眠
void *buyTicket(void *arg) { while(tickets>0) { pthread_mutex_lock(&mutex); printf("%p窗口卖出一张票%d ",pthread_self(),tickets); tickets--; pthread_mutex_unlock(&mutex); //防止只有一个窗口将票卖完 usleep(1);// } return NULL; }