C++核心准则CP.4:按照任务思考问题,而不是线程
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(示例)
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()以外,标准库功能都是低层次,面向机器,线程/锁层次的。这些作为基础有必要,但是我们必须努力提高抽象的层次:为了生产性,为了可靠性,也为了性能。这是一个事关使用更高层次,更加面向应用的库的具有重大影响的话题(如果可能,将其构建在标注库功能的顶层)。
Enforcement(实施建议)
???
原文链接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#cp4-think-in-terms-of-tasks-rather-than-threads
觉得本文有帮助?请分享给更多人。
关注微信公众号【面向对象思考】轻松学习每一天!
面向对象开发,面向对象思考!