1. 问题引入
在编写多线程代码时,你是否遇到过数据错乱的情况?比如多个线程同时操作一个共享变量,结果却出现了负数或丢失更新。这通常是因为缺乏同步机制导致的。
本章我们通过一个经典的买票场景来剖析这个问题,并学习如何使用互斥锁来解决它。
2. 抢票案例:竞态条件的复现
假设我们有 100 张电影票,5 个线程同时去抢。如果不加保护,会发生什么?
#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::(i);
threads.(routine, name);
}
(& thread : threads) {
thread.();
}
;
}


