前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则CP.4:按照任务思考问题,而不是线程

C++核心准则CP.4:按照任务思考问题,而不是线程

作者头像
面向对象思考
发布2020-07-03 17:06:58
3120
发布2020-07-03 17:06:58
举报

CP.4: Think in terms of tasks, rather than threads

CP.4:按照任务思考问题,而不是线程

Reason(原因)

A thread is an implementation concept, a way of thinking about the machine. A task is an application notion, something you'd like to do, preferably concurrently with other tasks. Application concepts are easier to reason about.

线程是实现层面的概念,一种理解机器动作的方式。任务是应用层面的观念,你希望它可以和其他任务并发执行。应用概念更容易理解。

Example(示例)

代码语言:javascript
复制
void some_fun()
{
    std::string msg, msg2;
    std::thread publisher([&] { msg = "Hello"; });       // bad: less expressive
                                                         //      and more error-prone
    auto pubtask = std::async([&] { msg2 = "Hello"; });  // OK
    // ...
    publisher.join();
}

Note(注意)

With the exception of async(), the standard-library facilities are low-level, machine-oriented, threads-and-lock level. This is a necessary foundation, but we have to try to raise the level of abstraction: for productivity, for reliability, and for performance. This is a potent argument for using higher level, more applications-oriented libraries (if possibly, built on top of standard-library facilities).

除了async()以外,标准库功能都是低层次,面向机器,线程/锁层次的。这些作为基础有必要,但是我们必须努力提高抽象的层次:为了生产性,为了可靠性,也为了性能。这是一个事关使用更高层次,更加面向应用的库的具有重大影响的话题(如果可能,将其构建在标注库功能的顶层)。

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#cp4-think-in-terms-of-tasks-rather-than-threads

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Reason(原因)
  • Note(注意)
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档