有时我必须使用它std::thread来加速我的应用程序.我也知道join()等待线程完成.这很容易理解,但是呼叫detach()和不呼叫之间的区别是什么?
我认为没有detach(),线程的方法将独立使用线程.
不分离:
void Someclass::Somefunction() {
//...
std::thread t([ ] {
printf("thread called without detach");
});
//some code here
}
Run Code Online (Sandbox Code Playgroud)
呼叫分离:
void Someclass::Somefunction() {
//...
std::thread t([ ] {
printf("thread called with detach");
});
t.detach();
//some code here
}
Run Code Online (Sandbox Code Playgroud) 我boost::thread使用new运算符创建对象并继续而不等待此线程完成其工作:
void do_work()
{
// perform some i/o work
}
boost::thread *thread = new boost::thread(&do_work);
Run Code Online (Sandbox Code Playgroud)
我想,有必要删除thread工作完成时.没有明确等待线程终止,最好的方法是什么?