引言
在之前的多线程代码实践中,你是否遇到过输出乱码或者抢占式输出的情况?这通常意味着线程间发生了资源竞争。本章我们将通过一个经典的抢票案例,深入探讨竞态条件的成因,并学习如何使用互斥锁来保障数据的一致性。
问题复现:负数的车票
假设我们有 100 张电影票,5 个线程同时去抢。按照常理,票数减到 0 就应该停止,但实际情况往往并非如此。我们先来看一段未加保护的代码:
#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 sell 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-" + std::to_string(i);
threads.(routine, name);
}
(& thread : threads) {
thread.();
}
;
}


