首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则:gsl::joining_thread好于std::thread

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

作者头像
面向对象思考
发布2020-07-07 10:41:08
6050
发布2020-07-07 10:41:08
举报

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();
    t2.join();
}  // one bad bug left
Note(注意)

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的代码:

  • Suggest use of gsl::joining_thread or C++20 std::jthread.
  • 建议使用gsl::joining_thread或者C++20引入的std::jthread.
  • Suggest "exporting ownership" to an enclosing scope if it detaches.
  • 如果需要分离线程,建议“输出所有权”到封闭的作用域。
  • Warn if it is not obvious whether a thread joins or detaches.
  • 如果不好判断线程会连结还是分离,报警。

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#cp25-prefer-gsljoining_thread-over-stdthread


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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • CP.25: Prefer gsl::joining_thread over std::thread
  • CP.25: gsl::joining_thread好于std::thread
    • Example(示例)
      • Note(注意)
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档