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

面向对象思考

共 1741字,需浏览 4分钟

 ·

2020-06-27 23:21

37fbed5829cb18ae98f9e7780379cb31.webp

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&);
Graph temperature_gradiants(const vector&);
Image altitude_map(const vector&);
// ...

void process_readings(const vector& 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:最好传值。


Enforcement(实施建议)

???


原文链接

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




觉得本文有帮助?请分享给更多人。

关注微信公众号【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!


浏览 35
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报