Getting started
2025/9/9大约 1 分钟
Getting started
从"Hello World" 开始
非并发打印 hello world
实现:
#include <iostream>
int main()
{
std::cout << "Hello World\n";
return 0;
}并发打印
实现:
#include <iostream>
#include <thread>
void hello()
{
std::cout << "Hello Concurrent World\n";
}
int main()
{
std::thread t(hello);
t.join();
return 0;
}| 行号 | 功能 | 说明 |
|---|---|---|
| 2 | 线程类头文件 | 管理线程的相关定义 线程间通讯、数据保护等在其他头文件中 |
| 4-7 | 线程函数定义 | |
| 10 | 创建线程 | 通过定义thread 类对象开启一个线程,并将该线程绑定到thread 对象 |
| 11 | 等待子线程结束 |
initial function
[!quote]
every thread has to have an initial function, where the new thread of execution begins.
每个线程都有一个 initial function - 入口函数。每个进程从主线程开始执行,main() 就是主线程的initial function。
这里hello 是子线程的initial function。
lunching thread
和正常的函数调用不同,创建线程对象并绑定initial function 后线程就会启动(initial function被调用)。
waiting for thread end
[!quote]
If it didn't wait for the new thread to finish, it would merrily continue to the end of main() and end the program - possibly before the new thread had a chance to run.
子线程创建后并不影响当前线程的执行(没有其他因素),如果main()-主线程结束,那么进程被销毁,子线程可能没有执行就被销毁。
不等待子线程
结果:
Hello Concurrent World
terminate called without an active exception