CP.23: Think of a joining thread as a scoped container
CP.23:将连结线程看作范围化的容器
To maintain pointer safety and avoid leaks, we need to consider what pointers are used by a thread. If a thread joins, we can safely pass pointers to objects in the scope of the thread and its enclosing scopes.
为了维持指针安全并避免泄露,我们需要考虑哪些指针被线程使用。如果存在线程连结,我们可以安全地在线程范围内传递对象的指针并关闭该范围。
Example(示例)
void f(int* p)
{
// ...
*p = 99;
// ...
}
int glob = 33;
void some_fct(int* p)
{
int x = 77;
joining_thread t0(f, &x); // OK
joining_thread t1(f, p); // OK
joining_thread t2(f, &glob); // OK
auto q = make_unique<int>(99);
joining_thread t3(f, q.get()); // OK
// ...
}
A gsl::joining_thread is a std::thread with a destructor that joins and that cannot be detached(). By "OK" we mean that the object will be in scope ("live") for as long as a thread can use the pointer to it. The fact that threads run concurrently doesn't affect the lifetime or ownership issues here; these threads can be seen as just a function object called from some_fct.
gsl::joining_thread是增加了调用了joins的析构函数而不能被detatched的std::thread。通过”OK“这个词我们想表达的是只要使用指针的线程存在,该指针指向的对象就会留在范围内(并保持可用状态)。这里,线程并发的事实不会影响生命周期或者所有权问题;可以认为线程就是一个被somt_ft调用的函数对象。
Enforcement(实施建议)
Ensure that joining_threads don't detach(). After that, the usual lifetime and ownership (for local objects) enforcement applies.
确认连结线程不会被detach。然后确认通常的生命周期和(针对局部对象的)所有权原则被适用了。
原文链接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#cp23-think-of-a-joining-thread-as-a-scoped-container