引言
在之前的多线程学习中,我们常遇到乱码或抢占输出的问题。这背后往往隐藏着更深层的并发隐患。本章我们通过一个经典的买票场景,深入剖析线程间的竞争关系,并学习如何用互斥锁来保障数据安全。
问题的根源:竞态条件
假设我们有 100 张电影票,5 个线程同时抢票。如果直接操作共享变量 ticket,会发生什么?
#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 shell ticket, now tickets number:%d\n", name.c_str(), ticket);
} else {
std::cout << ticket << std::endl;
break;
}
}
}
int main() {
std::vector<std::thread> threads;
for (int i = 0; i < 5; i++) {
std::string name = "thread-";
name += std::to_string(i);
threads.(routine, name);
}
(& thread : threads) {
thread.();
}
;
}


