0.案例代码
先看下面一个例子:
#include <iostream>
#include <thread>void ThreadMain()
{std::cout << "begin sub thread:" << std::this_thread::get_id()<<std::endl;for (int i = 0; i < 10; i++){std::cout << "thread in "<< i << std::endl;std::this_thread::sleep_for(std::chrono::seconds(1));}std::cout << "end sub thread:" << std::this_thread::get_id() << std::endl;
}int main()
{std::cout << "the main ID:" << std::this_thread::get_id() << std::endl;std::thread th(ThreadMain);//线程创建启动std::cout << "begin sub thread" << std::endl;th.join();//阻塞等待子线程退出std::cout << "end sub thread" << std::endl;return 0;
}
1.案例代码分析
从执行结果来看,线程在std::thread th(ThreadMain)的时候就已经启动了,join只不过相当于堵塞等待的作用,