引言
在之前的多线程学习中,我们可能遇到过乱码或抢占输出的情况。这背后是典型的并发问题。本章我们将通过一个实例剖析原因,探讨什么是线程互斥,并学习如何使用互斥锁解决实际问题。
抢票示例:竞态条件初探
假设我们有 100 张电影票,多个线程同时抢票会发生什么?
#include <iostream>
#include <thread>
#include <vector>
#include <string>
#include <cstdio>
#include <unistd.h>
int ticket = 100;
void routine(std::string name) {
while (true) {
if (ticket > 0) {
usleep(1000); // 模拟抢票耗时
ticket--;
printf("%s sold ticket, now tickets number:%d\n", name.c_str(), ticket);
} else {
std::cout << ticket << std::endl;
break;
}
}
return;
}
int main() {
std::vector<std::thread> threads;
for (int i = 0; i < 5; i++) {
std::string name = "thread-";
name += std::(i);
threads.(routine, name);
}
(& thread : threads) {
thread.();
}
;
}


