C++核心准则:gsl::joining_thread好于std::thread

CP.25: Prefer gsl::joining_thread over std::thread
CP.25: gsl::joining_thread好于std::thread
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
Example(示例)
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();