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(示例)
代码语言:javascript复制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