C++ 多线程编程指南

本文档基于 threads.cpp 文件,详细介绍 C++ 多线程编程的各种特性和用法。所有示例代码均包含中文注释,并确保可以使用 -fexec-charset=GBK 编译选项正常编译。

目录

基本线程创建

最基本的线程创建方式是使用 std::thread 类,并传入一个可调用对象(如函数)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <thread>

// 简单的线程函数
void printHello() {
std::cout << "Hello from thread!" << std::endl;
}

int main() {
// 创建线程并执行 printHello 函数
std::thread t1(printHello);

// 等待线程完成
t1.join();

std::cout << "Thread finished" << std::endl;

return 0;
}

带参数的线程

线程函数可以接收参数,参数会被复制到线程的内部存储空间。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <thread>
#include <string>

// 带参数的线程函数
void printMessage(const std::string& msg) {
std::cout << msg << std::endl;
}

int main() {
// 创建线程并传递参数
std::thread t2(printMessage, "Hello from parameterized thread!");

// 等待线程完成
t2.join();

return 0;
}

多线程并发

可以同时创建多个线程,它们会并发执行。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <thread>
#include <chrono>

// 计数函数
void countTo(int n) {
for (int i = 1; i <= n; ++i) {
std::cout << "Count: " << i << std::endl;
// 休眠 100 毫秒
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}

int main() {
// 创建两个线程,都执行 countTo 函数
std::thread t3(countTo, 5);
std::thread t4(countTo, 5);

// 等待两个线程完成
t3.join();
t4.join();

return 0;
}

互斥锁与线程安全

当多个线程访问共享资源时,需要使用互斥锁(mutex)来保证线程安全。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <thread>
#include <mutex>

int main() {
// 创建互斥锁
std::mutex mtx;
int counter = 0;

// 使用 lambda 表达式创建递增函数
auto increment = [&mtx, &counter]() {
for (int i = 0; i < 1000; ++i) {
// 使用 lock_guard 自动管理锁的生命周期
std::lock_guard<std::mutex> lock(mtx);
counter++;
}
};

// 创建两个线程执行递增操作
std::thread t5(increment);
std::thread t6(increment);

t5.join();
t6.join();

std::cout << "Final counter value: " << counter << std::endl;

return 0;
}

Unique Lock

std::unique_lock 提供了比 std::lock_guard 更灵活的锁管理,可以手动控制锁的获取和释放。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>

int main() {
std::mutex mtx2;
int sharedValue = 0;

// 修改共享值的函数
auto modifyValue = [&mtx2, &sharedValue](int amount) {
// 创建 unique_lock
std::unique_lock<std::mutex> lock(mtx2);
sharedValue += amount;
std::cout << "Modified value to: " << sharedValue << std::endl;

// 手动释放锁
lock.unlock();

// 执行不需要锁的操作
std::this_thread::sleep_for(std::chrono::milliseconds(50));
};

std::thread t7(modifyValue, 10);
std::thread t8(modifyValue, 20);

t7.join();
t8.join();

return 0;
}

条件变量

条件变量(condition_variable)用于线程间的通知机制,允许线程等待某个条件满足。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <chrono>

int main() {
std::mutex mtx3;
std::condition_variable cv;
bool ready = false;

// 工作线程函数
auto worker = [&mtx3, &cv, &ready]() {
std::unique_lock<std::mutex> lock(mtx3);
// 等待 ready 变为 true
cv.wait(lock, [&ready] { return ready; });
std::cout << "Worker thread is processing" << std::endl;
};

std::thread t9(worker);

// 主线程休眠 1 秒后设置 ready 为 true 并通知工作线程
std::this_thread::sleep_for(std::chrono::seconds(1));
{
std::lock_guard<std::mutex> lock(mtx3);
ready = true;
std::cout << "Signaling worker thread" << std::endl;
}
cv.notify_one();

t9.join();

return 0;
}

原子操作

原子操作(atomic)提供了无锁的线程安全操作,适用于简单的计数器等场景。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <thread>
#include <atomic>

int main() {
// 创建原子变量
std::atomic<int> atomicCounter(0);

// 原子递增函数
auto atomicIncrement = [&atomicCounter]() {
for (int i = 0; i < 1000; ++i) {
atomicCounter++;
}
};

std::thread t10(atomicIncrement);
std::thread t11(atomicIncrement);

t10.join();
t11.join();

std::cout << "Atomic counter value: " << atomicCounter << std::endl;

return 0;
}

Future 和 Promise

std::futurestd::promise 用于线程间的结果传递。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <thread>
#include <future>
#include <chrono>

int main() {
// 创建 promise 和 future
std::promise<int> promise;
std::future<int> future = promise.get_future();

// 设置值的函数
auto setValue = [&promise]() {
std::this_thread::sleep_for(std::chrono::seconds(1));
promise.set_value(42);
};

std::thread t12(setValue);

std::cout << "Waiting for value..." << std::endl;
// 阻塞等待获取值
int value = future.get();
std::cout << "Received value: " << value << std::endl;

t12.join();

return 0;
}

Async 异步任务

std::async 提供了更高级的异步任务管理方式。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <future>
#include <chrono>

int main() {
// 创建异步任务
auto asyncResult = std::async(std::launch::async, []() {
std::this_thread::sleep_for(std::chrono::seconds(2));
return 100;
});

std::cout << "Doing other work while async task runs..." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));

// 获取异步任务结果
int asyncValue = asyncResult.get();
std::cout << "Async result: " << asyncValue << std::endl;

return 0;
}

线程 ID

每个线程都有一个唯一的 ID,可以通过 std::this_thread::get_id() 获取。

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <thread>

int main() {
std::thread t13([]() {
std::cout << "Thread ID: " << std::this_thread::get_id() << std::endl;
});

std::cout << "Main Thread ID: " << std::this_thread::get_id() << std::endl;
t13.join();

return 0;
}

硬件并发支持

std::thread::hardware_concurrency() 可以获取系统支持的并发线程数。

1
2
3
4
5
6
7
8
9
#include <iostream>
#include <thread>

int main() {
unsigned int numThreads = std::thread::hardware_concurrency();
std::cout << "Number of concurrent threads supported: " << numThreads << std::endl;

return 0;
}

线程睡眠

std::this_thread::sleep_for() 可以让当前线程休眠指定的时间。

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <thread>
#include <chrono>

int main() {
std::cout << "Sleeping for 2 seconds..." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(2));
std::cout << "Woke up!" << std::endl;

return 0;
}

分离线程

分离线程(detached thread)不需要主线程等待其完成,会在后台运行。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <thread>
#include <chrono>

int main() {
std::thread t14([]() {
for (int i = 0; i < 5; ++i) {
std::cout << "Detached thread: " << i << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(200));
}
});

// 分离线程
t14.detach();

std::cout << "Main thread continues while detached thread runs" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(2));

return 0;
}

Packaged Task

std::packaged_task 用于包装可调用对象,以便异步执行并获取结果。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <thread>
#include <future>
#include <chrono>

int main() {
// 创建 packaged_task
std::packaged_task<int(int, int)> task([](int a, int b) {
std::this_thread::sleep_for(std::chrono::seconds(1));
return a + b;
});

// 获取 future
std::future<int> taskFuture = task.get_future();

// 在新线程中执行任务
std::thread t15(std::move(task), 10, 20);

std::cout << "Waiting for packaged task result..." << std::endl;
// 获取任务结果
int taskResult = taskFuture.get();
std::cout << "Task result: " << taskResult << std::endl;

t15.join();

return 0;
}

Shared Future

std::shared_future 允许多个线程共享同一个 future 的结果。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <thread>
#include <future>
#include <chrono>
#include <string>

int main() {
std::promise<int> sharedPromise;
// 创建 shared_future
std::shared_future<int> sharedFuture = sharedPromise.get_future().share();

// 等待并打印结果的函数
auto waitAndPrint = [&sharedFuture](const std::string& name) {
int result = sharedFuture.get();
std::cout << name << " got result: " << result << std::endl;
};

// 创建两个线程共享同一个 future
std::thread t16(waitAndPrint, "Thread 1");
std::thread t17(waitAndPrint, "Thread 2");

// 1 秒后设置值
std::this_thread::sleep_for(std::chrono::seconds(1));
sharedPromise.set_value(999);

t16.join();
t17.join();

return 0;
}

完整示例代码

以下是包含所有功能的完整示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <future>
#include <chrono>
#include <vector>
#include <string>

// 简单的线程函数
void printHello() {
std::cout << "Hello from thread!" << std::endl;
}

// 带参数的线程函数
void printMessage(const std::string& msg) {
std::cout << msg << std::endl;
}

// 计数函数
void countTo(int n) {
for (int i = 1; i <= n; ++i) {
std::cout << "Count: " << i << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}

int main() {
std::cout << "=== 基本线程 ===" << std::endl;
std::thread t1(printHello);
t1.join();
std::cout << "Thread finished" << std::endl;

std::cout << "\n=== 带参数的线程 ===" << std::endl;
std::thread t2(printMessage, "Hello from parameterized thread!");
t2.join();

std::cout << "\n=== 多线程 ===" << std::endl;
std::thread t3(countTo, 5);
std::thread t4(countTo, 5);

t3.join();
t4.join();

std::cout << "\n=== 互斥锁线程安全 ===" << std::endl;
std::mutex mtx;
int counter = 0;

auto increment = [&mtx, &counter]() {
for (int i = 0; i < 1000; ++i) {
std::lock_guard<std::mutex> lock(mtx);
counter++;
}
};

std::thread t5(increment);
std::thread t6(increment);

t5.join();
t6.join();
std::cout << "Final counter value: " << counter << std::endl;

std::cout << "\n=== Unique Lock ===" << std::endl;
std::mutex mtx2;
int sharedValue = 0;

auto modifyValue = [&mtx2, &sharedValue](int amount) {
std::unique_lock<std::mutex> lock(mtx2);
sharedValue += amount;
std::cout << "Modified value to: " << sharedValue << std::endl;
lock.unlock();
std::this_thread::sleep_for(std::chrono::milliseconds(50));
};

std::thread t7(modifyValue, 10);
std::thread t8(modifyValue, 20);

t7.join();
t8.join();

std::cout << "\n=== 条件变量 ===" << std::endl;
std::mutex mtx3;
std::condition_variable cv;
bool ready = false;

auto worker = [&mtx3, &cv, &ready]() {
std::unique_lock<std::mutex> lock(mtx3);
cv.wait(lock, [&ready] { return ready; });
std::cout << "Worker thread is processing" << std::endl;
};

std::thread t9(worker);

std::this_thread::sleep_for(std::chrono::seconds(1));
{
std::lock_guard<std::mutex> lock(mtx3);
ready = true;
std::cout << "Signaling worker thread" << std::endl;
}
cv.notify_one();

t9.join();

std::cout << "\n=== 原子操作 ===" << std::endl;
std::atomic<int> atomicCounter(0);

auto atomicIncrement = [&atomicCounter]() {
for (int i = 0; i < 1000; ++i) {
atomicCounter++;
}
};

std::thread t10(atomicIncrement);
std::thread t11(atomicIncrement);

t10.join();
t11.join();
std::cout << "Atomic counter value: " << atomicCounter << std::endl;

std::cout << "\n=== Future 和 Promise ===" << std::endl;
std::promise<int> promise;
std::future<int> future = promise.get_future();

auto setValue = [&promise]() {
std::this_thread::sleep_for(std::chrono::seconds(1));
promise.set_value(42);
};

std::thread t12(setValue);

std::cout << "Waiting for value..." << std::endl;
int value = future.get();
std::cout << "Received value: " << value << std::endl;

t12.join();

std::cout << "\n=== Async with Future ===" << std::endl;
auto asyncResult = std::async(std::launch::async, []() {
std::this_thread::sleep_for(std::chrono::seconds(2));
return 100;
});

std::cout << "Doing other work while async task runs..." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));

int asyncValue = asyncResult.get();
std::cout << "Async result: " << asyncValue << std::endl;

std::cout << "\n=== 线程 ID ===" << std::endl;
std::thread t13([]() {
std::cout << "Thread ID: " << std::this_thread::get_id() << std::endl;
});

std::cout << "Main Thread ID: " << std::this_thread::get_id() << std::endl;
t13.join();

std::cout << "\n=== 线程硬件并发 ===" << std::endl;
unsigned int numThreads = std::thread::hardware_concurrency();
std::cout << "Number of concurrent threads supported: " << numThreads << std::endl;

std::cout << "\n=== 线程睡眠 ===" << std::endl;
std::cout << "Sleeping for 2 seconds..." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(2));
std::cout << "Woke up!" << std::endl;

std::cout << "\n=== 分离线程 ===" << std::endl;
std::thread t14([]() {
for (int i = 0; i < 5; ++i) {
std::cout << "Detached thread: " << i << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(200));
}
});
t14.detach();
std::cout << "Main thread continues while detached thread runs" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(2));

std::cout << "\n=== Packaged Task ===" << std::endl;
std::packaged_task<int(int, int)> task([](int a, int b) {
std::this_thread::sleep_for(std::chrono::seconds(1));
return a + b;
});

std::future<int> taskFuture = task.get_future();
std::thread t15(std::move(task), 10, 20);

std::cout << "Waiting for packaged task result..." << std::endl;
int taskResult = taskFuture.get();
std::cout << "Task result: " << taskResult << std::endl;

t15.join();

std::cout << "\n=== Shared Future ===" << std::endl;
std::promise<int> sharedPromise;
std::shared_future<int> sharedFuture = sharedPromise.get_future().share();

auto waitAndPrint = [&sharedFuture](const std::string& name) {
int result = sharedFuture.get();
std::cout << name << " got result: " << result << std::endl;
};

std::thread t16(waitAndPrint, "Thread 1");
std::thread t17(waitAndPrint, "Thread 2");

std::this_thread::sleep_for(std::chrono::seconds(1));
sharedPromise.set_value(999);

t16.join();
t17.join();

return 0;
}

编译与运行

编译命令

使用 -fexec-charset=GBK 选项编译代码,以确保中文输出正常:

1
g++ -std=c++11 -fexec-charset=GBK threads.cpp -o threads.exe

运行结果

运行编译生成的可执行文件,将看到各种线程操作的输出:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
=== 基本线程 ===
Hello from thread!
Thread finished

=== 带参数的线程 ===
Hello from parameterized thread!

=== 多线程 ===
Count: 1
Count: 1
Count: 2
Count: 2
Count: 3
Count: 3
Count: 4
Count: 4
Count: 5
Count: 5

=== 互斥锁线程安全 ===
Final counter value: 2000

=== Unique Lock ===
Modified value to: 10
Modified value to: 30

=== 条件变量 ===
Signaling worker thread
Worker thread is processing

=== 原子操作 ===
Atomic counter value: 2000

=== Future 和 Promise ===
Waiting for value...
Received value: 42

=== Async with Future ===
Doing other work while async task runs...
Async result: 100

=== 线程 ID ===
Main Thread ID: 1
Thread ID: 2

=== 线程硬件并发 ===
Number of concurrent threads supported: 4

=== 线程睡眠 ===
Sleeping for 2 seconds...
Woke up!

=== 分离线程 ===
Main thread continues while detached thread runs
Detached thread: 0
Detached thread: 1
Detached thread: 2
Detached thread: 3
Detached thread: 4

=== Packaged Task ===
Waiting for packaged task result...
Task result: 30

=== Shared Future ===
Thread 1 got result: 999
Thread 2 got result: 999

总结

本文档介绍了 C++ 中多线程编程的各种特性和用法,包括:

  • 基本线程创建和管理
  • 线程参数传递
  • 多线程并发执行
  • 互斥锁和线程安全
  • 条件变量和线程通知
  • 原子操作
  • Future、Promise 和异步任务
  • 线程 ID 和硬件并发
  • 线程睡眠和分离线程
  • Packaged Task 和 Shared Future

通过这些工具和技术,可以编写出高效、安全的多线程应用程序,充分利用现代计算机的多核处理能力。

threads.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <future>
#include <chrono>
#include <vector>
#include <string>

void printHello() {
std::cout << "Hello from thread!" << std::endl;
}

void printMessage(const std::string& msg) {
std::cout << msg << std::endl;
}

void countTo(int n) {
for (int i = 1; i <= n; ++i) {
std::cout << "Count: " << i << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}

int main() {
std::cout << "=== Basic Thread ===" << std::endl;
std::thread t1(printHello);
t1.join();
std::cout << "Thread finished" << std::endl;

std::cout << "\n=== Thread with Parameters ===" << std::endl;
std::thread t2(printMessage, "Hello from parameterized thread!");
t2.join();

std::cout << "\n=== Multiple Threads ===" << std::endl;
std::thread t3(countTo, 5);
std::thread t4(countTo, 5);

t3.join();
t4.join();

std::cout << "\n=== Mutex for Thread Safety ===" << std::endl;
std::mutex mtx;
int counter = 0;

auto increment = [&mtx, &counter]() {
for (int i = 0; i < 1000; ++i) {
std::lock_guard<std::mutex> lock(mtx);
counter++;
}
};

std::thread t5(increment);
std::thread t6(increment);

t5.join();
t6.join();
std::cout << "Final counter value: " << counter << std::endl;

std::cout << "\n=== Unique Lock ===" << std::endl;
std::mutex mtx2;
int sharedValue = 0;

auto modifyValue = [&mtx2, &sharedValue](int amount) {
std::unique_lock<std::mutex> lock(mtx2);
sharedValue += amount;
std::cout << "Modified value to: " << sharedValue << std::endl;
lock.unlock();
std::this_thread::sleep_for(std::chrono::milliseconds(50));
};

std::thread t7(modifyValue, 10);
std::thread t8(modifyValue, 20);

t7.join();
t8.join();

std::cout << "\n=== Condition Variable ===" << std::endl;
std::mutex mtx3;
std::condition_variable cv;
bool ready = false;

auto worker = [&mtx3, &cv, &ready]() {
std::unique_lock<std::mutex> lock(mtx3);
cv.wait(lock, [&ready] { return ready; });
std::cout << "Worker thread is processing" << std::endl;
};

std::thread t9(worker);

std::this_thread::sleep_for(std::chrono::seconds(1));
{
std::lock_guard<std::mutex> lock(mtx3);
ready = true;
std::cout << "Signaling worker thread" << std::endl;
}
cv.notify_one();

t9.join();

std::cout << "\n=== Atomic Operations ===" << std::endl;
std::atomic<int> atomicCounter(0);

auto atomicIncrement = [&atomicCounter]() {
for (int i = 0; i < 1000; ++i) {
atomicCounter++;
}
};

std::thread t10(atomicIncrement);
std::thread t11(atomicIncrement);

t10.join();
t11.join();
std::cout << "Atomic counter value: " << atomicCounter << std::endl;

std::cout << "\n=== Future and Promise ===" << std::endl;
std::promise<int> promise;
std::future<int> future = promise.get_future();

auto setValue = [&promise]() {
std::this_thread::sleep_for(std::chrono::seconds(1));
promise.set_value(42);
};

std::thread t12(setValue);

std::cout << "Waiting for value..." << std::endl;
int value = future.get();
std::cout << "Received value: " << value << std::endl;

t12.join();

std::cout << "\n=== Async with Future ===" << std::endl;
auto asyncResult = std::async(std::launch::async, []() {
std::this_thread::sleep_for(std::chrono::seconds(2));
return 100;
});

std::cout << "Doing other work while async task runs..." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));

int asyncValue = asyncResult.get();
std::cout << "Async result: " << asyncValue << std::endl;

std::cout << "\n=== Thread ID ===" << std::endl;
std::thread t13([]() {
std::cout << "Thread ID: " << std::this_thread::get_id() << std::endl;
});

std::cout << "Main Thread ID: " << std::this_thread::get_id() << std::endl;
t13.join();

std::cout << "\n=== Thread Hardware Concurrency ===" << std::endl;
unsigned int numThreads = std::thread::hardware_concurrency();
std::cout << "Number of concurrent threads supported: " << numThreads << std::endl;

std::cout << "\n=== Thread Sleep ===" << std::endl;
std::cout << "Sleeping for 2 seconds..." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(2));
std::cout << "Woke up!" << std::endl;

std::cout << "\n=== Detached Thread ===" << std::endl;
std::thread t14([]() {
for (int i = 0; i < 5; ++i) {
std::cout << "Detached thread: " << i << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(200));
}
});
t14.detach();
std::cout << "Main thread continues while detached thread runs" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(2));

std::cout << "\n=== Packaged Task ===" << std::endl;
std::packaged_task<int(int, int)> task([](int a, int b) {
std::this_thread::sleep_for(std::chrono::seconds(1));
return a + b;
});

std::future<int> taskFuture = task.get_future();
std::thread t15(std::move(task), 10, 20);

std::cout << "Waiting for packaged task result..." << std::endl;
int taskResult = taskFuture.get();
std::cout << "Task result: " << taskResult << std::endl;

t15.join();

std::cout << "\n=== Shared Future ===" << std::endl;
std::promise<int> sharedPromise;
std::shared_future<int> sharedFuture = sharedPromise.get_future().share();

auto waitAndPrint = [&sharedFuture](const std::string& name) {
int result = sharedFuture.get();
std::cout << name << " got result: " << result << std::endl;
};

std::thread t16(waitAndPrint, "Thread 1");
std::thread t17(waitAndPrint, "Thread 2");

std::this_thread::sleep_for(std::chrono::seconds(1));
sharedPromise.set_value(999);

t16.join();
t17.join();

return 0;
}