引言
在多进程或多线程开发中,我们经常遇到数据错乱的问题。比如五个线程同时抢 100 张票,最后票数竟然变成了负数。这背后的元凶就是经典的竞态条件(Race Condition)。
本章我们将通过一个买票的例子,剖析问题根源,并引入互斥锁来解决它。
问题复现:买票场景
假设我们有 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 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-";
name += std::(i);
threads.(routine, name);
}
(& thread : threads) {
thread.();
}
;
}


