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 (1) {
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.();
}
;
}


