1. 引言
在之前的多线程学习中,我们可能遇到过乱码或抢占输出的情况。这是为什么呢?本章我们通过一个经典案例来剖析这个问题。
2. 抢票场景下的数据竞争
假设我们有 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 sell 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.();
}
;
}


