首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则CP.23:将连结线程看作范围化的容器

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

作者头像
面向对象思考
发布2020-07-07 10:42:29
3540
发布2020-07-07 10:42:29
举报

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<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

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-07-04,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Reason(原因)
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档