Reason(原因)
A joining_thread is a thread that joins at the end of its scope. Detached threads are hard to monitor. It is harder to ensure absence of errors in detached threads (and potentially detached threads).
joining_thread是一种在和作用域连结的线程。分离之后的线程很难监控。很难保证分离之后(或者存在潜在的分离可能性)的线程中不存在错误。
Example, bad(反面示例)
void f() { std::cout << "Hello "; }
struct F {
void operator()() const { std::cout << "parallel world "; }
};
int main()
{
std::thread t1{f}; // f() executes in separate thread
std::thread t2{F()}; // F()() executes in separate thread
} // spot the bugs
void f() { std::cout << "Hello "; }
struct F {
void operator()() const { std::cout << "parallel world "; }
};
int main()
{
std::thread t1{f}; // f() executes in separate thread
std::thread t2{F()}; // F()() executes in separate thread
t1.join();
t2.join();
} // one bad bug left
Make "immortal threads" globals, put them in an enclosing scope, or put them on the free store rather than detach(). Don't detach.
将“永远有效的线程"定义为全局的,将它们限制在一个封闭的作用域,或者将它们放在自由存储中而不是分离它们。不要分离线程。
Note(注意)
Because of old code and third party libraries using std::thread, this rule can be hard to introduce.
因为旧代码和第三方库在使用std::thread,本准则很难推广。
Enforcement(实施建议)
Flag uses of std::thread:
标记使用std::thread的代码:
原文链接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#cp25-prefer-gsljoining_thread-over-stdthread