步骤:
- a) 包含头文件
- b) 自定义线程执行函数
- c) 创建子线程thread thread1(thread_fun); 子线程需要完成的任务在thread_fun写
- d) join() :汇合,阻塞主线程并等待子线程执行完,继续往下执行主线程
整个进程执行的完毕结束的标志是主线程结束; 此时,如果其他子线程还没有执行完毕,那么子线程也会被操作系统强行终止,系统抛出异常;良好的程序应该是主线程等待子线程执行完毕后,自己才能退出;
#include <thread>
#include <iostream>
using namespace std;
void thread_fun()
{
cout << "sub thread begin,thread ID: " << this_thread::get_id() << endl;
for (int i = 0; i < 10; i++) {
cout << "i=" << i << endl;
this_thread::sleep_for(chrono::seconds(1)); // 1000ms
}
cout << "sub thread main is over,thread ID:" << this_thread::get_id()
<< endl;
}
int main(int argc, char *argv[])
{
cout << "main thread begin,thread ID: " << this_thread::get_id() << endl;
//线程创建启动
thread thread1(thread_fun);
//阻塞等待子线程退出
thread1.join();
cout << "main thread is over,thread ID: " << this_thread::get_id() << endl;
return 0;
}