前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则CP.31:在线程之间以传值方式传递少量数据,而不是传递引用或指针

C++核心准则CP.31:在线程之间以传值方式传递少量数据,而不是传递引用或指针

作者头像
面向对象思考
发布2020-07-14 16:19:22
7480
发布2020-07-14 16:19:22
举报
文章被收录于专栏:C++核心准则原文翻译

CP.31: Pass small amounts of data between threads by value, rather than by reference or pointer

CP.31:在线程之间以传值方式传递少量数据,而不是传递引用或指针

Reason(原因)

Copying a small amount of data is cheaper to copy and access than to share it using some locking mechanism. Copying naturally gives unique ownership (simplifies code) and eliminates the possibility of data races.

以拷贝形式提供的少量数据的复制和访问成本会低于使用某种锁定机制的共享。拷贝操作天然保证所有权的唯一性(简化代码),避免可能出现的数据竞争。

Note(注意)

Defining "small amount" precisely is impossible.

不可能确切定义什么是“少量”。

Example(示例)

代码语言:javascript
复制
string modify1(string);
void modify2(string&);

void fct(string& s)
{
    auto res = async(modify1, s);
    async(modify2, s);
}

The call of modify1 involves copying two string values; the call of modify2 does not. On the other hand, the implementation of modify1 is exactly as we would have written it for single-threaded code, whereas the implementation of modify2 will need some form of locking to avoid data races. If the string is short (say 10 characters), the call of modify1 can be surprisingly fast; essentially all the cost is in the thread switch. If the string is long (say 1,000,000 characters), copying it twice is probably not a good idea.

调用modify1的过程包含两次拷贝string的值;调用modify2的过程就不会。另一方面,(多任务环境下,译者注)modify1的实现和单线程代码完全相同,而modify2会需要某种形式的互斥锁以避免数据竞争。如果是短string(比如说10个字符),调用modify1的过程会出奇地快,基本上就是线程切换的成本。如果是长string(例如1,000,000个字符),拷贝两次可能不是一个好主意。

Note that this argument has nothing to do with async as such. It applies equally to considerations about whether to use message passing or shared memory.

注意参数处理过程没有为异步操作做任何事。这个判断同样适用于考虑使用消息还是共享内存的情况。

Enforcement(实施建议)

???

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#cp31-pass-small-amounts-of-data-between-threads-by-value-rather-than-by-reference-or-pointer

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • CP.31: Pass small amounts of data between threads by value, rather than by reference or pointer
  • Reason(原因)
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档