#include <iostream>
#include <thread>
void thread_fun()
{
std::cout<<"我是线程函数"<<std::endl;
}
int main()
{
std::thread t(thread_fun);
t.join(); //运行线程函数,主线程阻塞在这里,直到thread_fun()执行完毕
return 0;
}
#include <iostream>
#include <thread>
void thread_fun()
{
std::cout<<"我是线程函数"<<std::endl;
}
int main()
{
std::thread t(thread_fun);
t.detach(); //运行线程函数,不阻塞主线程
return 0;
}
控制台没有显示任何字符,原因:使用detach开启子线程没有阻塞主线程,主线程已经执行完毕。
#include <iostream>
#include <thread>
void thread_fun()
{
std::cout<<"我是线程函数"<<std::endl;
}
int main()
{
std::thread t(thread_fun);
t.detach(); //运行线程函数,不阻塞主线程
t.join(); //detach后,不能再使用join
return 0;
}
结论:detach后,不能再使用join
#include <iostream>
#include <thread>
void thread_fun()
{
std::cout<<"我是线程函数"<<std::endl;
}
int main()
{
std::thread t(thread_fun);
t.detach(); //运行线程函数,不阻塞主线程
if(t.joinable())
{
t.join(); //detach后,不能再使用join
}
else
{
std::cout<<"detach后,不能再使用join"<<std::endl;
}
return 0;
}
结论:可以使用joinable()判断是否可以join()
原文链接: https://www.cnblogs.com/guozhikai/p/6105096.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/244600
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!