C++核心準則CP.4:按照任務(wù)思考問題,而不是線程

CP.4: Think in terms of tasks, rather than threads
CP.4:按照任務(wù)思考問題,而不是線程
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.
線程是實現(xiàn)層面的概念,一種理解機器動作的方式。任務(wù)是應(yīng)用層面的觀念,你希望它可以和其他任務(wù)并發(fā)執(zhí)行。應(yīng)用概念更容易理解。
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()以外,標準庫功能都是低層次,面向機器,線程/鎖層次的。這些作為基礎(chǔ)有必要,但是我們必須努力提高抽象的層次:為了生產(chǎn)性,為了可靠性,也為了性能。這是一個事關(guān)使用更高層次,更加面向應(yīng)用的庫的具有重大影響的話題(如果可能,將其構(gòu)建在標注庫功能的頂層)。
Enforcement(實施建議)
???
原文鏈接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#cp4-think-in-terms-of-tasks-rather-than-threads
覺得本文有幫助?請分享給更多人。
關(guān)注微信公眾號【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
