1 join方法
代码示例:
#include <iostream>
#include <thread>
void HelloWorld()
{
std::cout << "hello world" << std::endl;
}
int main()
{
std::thread helloWorldThread(HelloWorld);
helloWorldThread.join();
getchar();
return 0;
}
在上述代码中,线程函数HelloWorld将会被子线程helloWorldThread启动,并运行在该线程中,而join函数会阻塞线程,直到线程函数执行完毕,如果线程函数有返回值,那么返回值将会被忽略。
2 detach方法
如果我们不想线程被阻塞怎么办?使用detach方式,但是风险很高,你可以联想C++的野指针。
在下列代码中,线程函数HelloWorld将会被子线程helloWorldThread启动,并运行在该线程中,detach方法会将线程与线程对象分离,让子线程作为后台线程执行,当前的线程也不会被阻塞。但是,线程detach之后无法与当前线程取得任何联系,也就是说detach之后无法使用join等待线程执行完成,因为线程detach之后何时执行完毕取决于其函数体内的运算逻辑。
代码示例:
#include <iostream>
#include <thread>
void HelloWorld()
{
std::cout << "hello world" << std::endl;
}
int main()
{
std::thread helloWorldThread(HelloWorld);
helloWorldThread.detach();
// do other things 马上可以做其他事情,不会被阻塞
getchar();
return 0;
}
如果有兴趣,可以访问我的个站:www.stubbornhuang.com