C++ 从入门到精通之十

大纲

C++ 并发编程

线程运行的开始和结束

特别注意

  • 进程是否执行完毕,是以主线程是否执行完为标志的。主线程一旦结束,整个进程就会终止,未执行完的子线程也会被操作系统强制结束。因此,若希望子线程继续运行,那么就必须保持主线程不结束。
  • 值得一提的是,只有当子线程被设计为必须完成的核心任务时,主线程提前结束导致子线程被操作系统强杀,这才属于程序缺陷或不合格的程序设计;若子线程设计为守护线程或完成辅助性任务,其随主线程终止属于正常行为。
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
#include <chrono>
#include <iostream>
#include <thread>

void func() {
std::cout << "sub thread start." << std::endl;
for (int i = 1; i <= 5; ++i) {
std::cout << i << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
std::cout << "sub thread end." << std::endl;
}

int main() {
std::cout << "main thread start." << std::endl;

// 创建并启动一个普通线程
std::thread t(func);

// 阻塞主线程,让主线程等待子线程执行结束,然后再往下执行
// 注意:如果这里不让主线程阻塞等待子线程执行结束,会导致程序意外退出(直接崩溃)
t.join();

std::cout << "main thread end." << std::endl;
return 0;
}

程序运行输出的结果如下:

1
2
3
4
5
6
7
8
9
main thread start.
sub thread start.
1
2
3
4
5
sub thread end.
main thread end.

创建线程的其他常见方式