前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则CP.3:尽量不要显式共享可写数据

C++核心准则CP.3:尽量不要显式共享可写数据

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

CP.3: Minimize explicit sharing of writable data

CP.3:尽量不要显式共享可写数据

Reason(原因)

If you don't share writable data, you can't have a data race. The less sharing you do, the less chance you have to forget to synchronize access (and get data races). The less sharing you do, the less chance you have to wait on a lock (so performance can improve).

如果不共享可写数据,就不会发生数据竞争。你共享得越少,忘记同步访问操作(并发生数据竞争)的可能性就越小。你共享得越少,等待锁释放的需求就越少(因而可以提高性能)。

Example(示例)

bool validate(const vector<Reading>&);
Graph<Temp_node> temperature_gradiants(const vector<Reading>&);
Image altitude_map(const vector<Reading>&);
// ...

void process_readings(const vector<Reading>& surface_readings)
{
    auto h1 = async([&] { if (!validate(surface_readings)) throw Invalid_data{}; });
    auto h2 = async([&] { return temperature_gradiants(surface_readings); });
    auto h3 = async([&] { return altitude_map(surface_readings); });
    // ...
    h1.get();
    auto v2 = h2.get();
    auto v3 = h3.get();
    // ...
}

Without those consts, we would have to review every asynchronously invoked function for potential data races on surface_readings. Making surface_readings be const (with respect to this function) allow reasoning using only the function body.

如果没有常量修饰符,我们必须检查函数的所有的非同步调用以防止surface_readings发生潜在的数据竞争。在函数中将suface__readings定义为常量之后可以推断出其在函数体内部的用法。

Note(注意)

Immutable data can be safely and efficiently shared. No locking is needed: You can't have a data race on a constant. See also CP.mess: Message Passing and CP.31: prefer pass by value.

无法修改的数据可以安全并高效地分享。不需要加锁:数据竞争无法在常量数据上发生。参照:CP.mess:消息传递和CP.31:最好传值。

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#cp3-minimize-explicit-sharing-of-writable-data

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档