Why does C++ try not to share writable data explicitly?
This article mainly explains "Why C++ tries not to share writable data explicitly". The content in the article is simple, clear and easy to learn and understand. Please follow the editor's train of thought. Let's study and learn why C++ tries not to share writable data explicitly.
CP.3: try not to explicitly share writable data
Reason (reason)
If writable data is not shared, there will be no data competition. The less you share, the less likely you are to forget synchronous access operations (and data contention). The less you share, the less you have to wait for the lock to be released (and thus improve performance).
Example (sample)
Bool validate (const vector&)
Graph temperature_gradiants (const vector&)
Image altitude_map (const vector&)
/ /...
Void process_readings (const vector& surface_readings)
{
Auto H2 = async ([&] {if (! validate (surface_readings)) throw Invalid_data {};})
Auto h3 = async ([&] {return temperature_gradiants (surface_readings);})
Auto h4 = async ([&] {return altitude_map (surface_readings);})
/ /...
H2.get ()
Auto v2 = h3.get ()
Auto v3 = h4.get ()
/ /...
}
If there is no constant modifier, we must check all asynchronous calls to the function to prevent potential data contention in surface_readings. After defining suface__readings as a constant in a function, its usage within the function body can be inferred.
Note (Note)
Data that cannot be modified can be safely and efficiently shared. No locking is required: data contention cannot occur on constant data. Refer to: CP.mess: message passing and CP.31: it is best to pass values.
Thank you for your reading, the above is the content of "Why C++ tries not to share writable data explicitly". After the study of this article, I believe you have a deeper understanding of why C++ tries not to share writable data explicitly, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!