CP.31:在线程之间以传值方式传递少量数据,而不是传递引用或指针
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(示例)
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
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有