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


