C++核心準(zhǔn)則CP.3:盡量不要顯式共享可寫數(shù)據(jù)

CP.3: Minimize explicit sharing of writable data
CP.3:盡量不要顯式共享可寫數(shù)據(jù)
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).
如果不共享可寫數(shù)據(jù),就不會發(fā)生數(shù)據(jù)競爭。你共享得越少,忘記同步訪問操作(并發(fā)生數(shù)據(jù)競爭)的可能性就越小。你共享得越少,等待鎖釋放的需求就越少(因而可以提高性能)。
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.
如果沒有常量修飾符,我們必須檢查函數(shù)的所有的非同步調(diào)用以防止surface_readings發(fā)生潛在的數(shù)據(jù)競爭。在函數(shù)中將suface__readings定義為常量之后可以推斷出其在函數(shù)體內(nèi)部的用法。
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.
無法修改的數(shù)據(jù)可以安全并高效地分享。不需要加鎖:數(shù)據(jù)競爭無法在常量數(shù)據(jù)上發(fā)生。參照:CP.mess:消息傳遞和CP.31:最好傳值。
Enforcement(實施建議)
???
原文鏈接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#cp3-minimize-explicit-sharing-of-writable-data
覺得本文有幫助?請分享給更多人。
關(guān)注微信公眾號【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
