温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C++中为什么gsl::joining_thread好于std::thread

发布时间:2021-11-25 15:56:28 来源:亿速云 阅读:124 作者:iii 栏目:大数据

本篇内容主要讲解“C++中为什么gsl::joining_thread好于std::thread”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“C++中为什么gsl::joining_thread好于std::thread”吧!

CP.25: gsl::joining_thread好于std::thread

Reason(原因)

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.

  • 如果不好判断线程会连结还是分离,报警。

到此,相信大家对“C++中为什么gsl::joining_thread好于std::thread”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++
AI