多线程 std::thread
std::thread 创建/join/detach、数据竞争、线程ID
多线程 std::thread
C++11 引入 std::thread——真正的跨平台多线程,不用 pthread 或 Windows API。
学完本章你将: 掌握 std::thread 创建/join/detach、数据竞争识别。
创建与等待
cpp
#include <iostream>
#include <thread>
void worker(int id, int delay_ms) {
std::this_thread::sleep_for(std::chrono::milliseconds(delay_ms));
std::cout << "Worker " << id << " 完成\n";
}
int main() {
std::thread t1(worker, 1, 200);
std::thread t2(worker, 2, 100);
// join —— 等待线程结束
t1.join();
t2.join();
std::cout << "全部完成\n";
return 0;
}
// 编译:g++ -std=c++17 -pthread main.cpp
detach vs join
cpp
std::thread t(worker, 1, 500);
// join —— 等待线程结束(安全)
t.join();
// detach —— 分离线程,独立运行(危险——可能访问已销毁的变量)
// t.detach();
// 分离后不能再 join,joinable() 返回 false
数据竞争
cpp
int counter = 0; // ❌ 两个线程同时修改——数据竞争
void increment() {
for (int i = 0; i < 100000; i++) {
counter++; // 不是原子操作!读-改-写三步
}
}
std::thread t1(increment);
std::thread t2(increment);
t1.join(); t2.join();
// counter 可能不是 200000——结果不确定!
线程 ID 与硬件并发
cpp
std::cout << std::this_thread::get_id() << "\n";
std::cout << "CPU 核心: " << std::thread::hardware_concurrency() << "\n";
// 让出 CPU
std::this_thread::yield();
// 睡眠
std::this_thread::sleep_for(std::chrono::seconds(1));