导航菜单

C++编程/多线程编程
课程进度 91% · 第17/18章17/18章 · 标签 1/3
1

创建和使用线程

使用C++11标准线程库创建和管理线程。

cpp
1
#include <iostream>
2
#include <thread>
3
#include <chrono>
4
using namespace std;
5
 
6
// 线程函数
7
void threadFunction(int id) {
8
for(int i = 0; i < 3; i++) {
9
cout << "线程 " << id << " 执行中..." << endl;
10
this_thread::sleep_for(chrono::seconds(1));
11
}
12
}
13
 
14
int main() {
15
cout << "主线程开始" << endl;
16
 
17
// 创建线程
18
thread t1(threadFunction, 1);
19
thread t2(threadFunction, 2);
20
 
21
// 等待线程完成
22
t1.join();
23
t2.join();
24
 
25
cout << "所有线程已完成" << endl;
26
return 0;
27
}
28
 
29
// 使用Lambda表达式
30
void lambdaThread() {
31
auto lambda = [](int x) {
32
cout << "Lambda线程: " << x << endl;
33
};
34
thread t(lambda, 100);
35
t.join();
36
}

📖join() 等待线程完成,detach() 将线程与主线程分离。线程函数可以是普通函数、Lambda 或函数对象

2

线程管理与同步

cpp
1
// 线程管理
2
void threadManagement() {
3
// 获取线程ID
4
thread::id this_id = this_thread::get_id();
5
 
6
// 获取CPU核心数
7
unsigned int n = thread::hardware_concurrency();
8
 
9
// 线程分离
10
thread detachThread([]{
11
cout << "分离线程运行" << endl;
12
});
13
detachThread.detach();
14
 
15
// 判断线程是否可join
16
thread t(threadFunction, 1);
17
if (t.joinable()) {
18
t.join();
19
}
20
}
21
 
22
// 线程局部存储
23
thread_local int threadLocalVar = 0;
24
 
25
void incrementLocal() {
26
threadLocalVar++;
27
cout << "线程本地变量: "
28
<< threadLocalVar << endl;
29
}