前言
在编写多线程代码时,我们常遇到乱码或抢占式输出。本章将探讨其成因并给出解决方案。
抢票示例
假设我们有 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;
}
}
return;
}
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.();
}
;
}


