C++核心准则CP.23:将连结线程看作范围化的容器

网友投稿 503 2022-11-13

C++核心准则CP.23:将连结线程看作范围化的容器

C++核心准则CP.23:将连结线程看作范围化的容器

CP.23: Think of a joining thread as a scoped container

CP.23:将连结线程看作范围化的容器

Reason(原因)

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(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。然后确认通常的生命周期和(针对局部对象的)所有权原则被适用了。

原文链接

​​的标准GUI 工具包tkinter,通过可执行的示例对23 个设计模式逐个进行说明。这样一方面可以使读者了解真实的软件开发工作中每个设计模式的运用场景和想要解决的问题;另一方面通过对这些问题的解决过程进行说明,让读者明白在编写代码时如何判断使用设计模式的利弊,并合理运用设计模式。

对设计模式感兴趣而且希望随学随用的读者通过本书可以快速跨越从理解到运用的门槛;希望学习Python GUI 编程的读者可以将本书中的示例作为设计和开发的参考;使用Python 语言进行图像分析、数据处理工作的读者可以直接以本书中的示例为基础,迅速构建自己的系统架构。

觉得本文有帮助?欢迎点赞并分享给更多的人。

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:C++核心准则ES.65:不要解引用无效指针
下一篇:使用Log4j2代码方式配置实现线程级动态控制
相关文章

 发表评论

暂时没有评论,来抢沙发吧~