引言
在多线程编程中,共享资源的并发访问往往会导致数据异常。比如经典的抢票场景,多个线程同时操作同一个票数变量,结果可能出现负数或重复扣减。本章将深入探讨这一现象的成因,并引入互斥锁机制来保障数据安全。
案例:抢票时的数据异常
假设有 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::to_string(i);
threads.(routine, name);
}
(& thread : threads) {
thread.();
}
;
}


