Thread safety of copy on write
c++, copy-on-write, multithreading
Solution
If you have data which can be shared between multiple threads (such as the `testValue` member in your case), you must synchronise all accesses to that data. "Synchronise" has a broad meaning here: it could be done using a mutex, by making the data atomic, or by explicitly invoking a memory barrier.
But you cannot skip on this. In a parallel world with multiple threads, CPU cores, CPUs and caches, there is no guarantee that a write by one thread will be visible to another thread if they don't "shake hands" on a synchronisation primitive. It is quite possible that thread T1's cache entry for `testValue` will not be updated when thread T2 writes into `testValue`, precisely because the HW cache management system sees "no synchronisation is happening, the threads don't access shared data, why should I torpedo performance by invalidating caches?"
The C++11 standard chapter [intro.multithread] goes into more detail than you'd like on this, but here's an informal Note from that chapter summarising the idea:
5 ... Informally, performing a release operation on A forces prior side effects on other memory locations to become visible to other threads that later perform a consume or an acquire operation on A. ...
Problem
I try to understand proper way of developing threadsafe applications. In current project I have following class : ``` class Test { public: void setVal(unsigned int val) { mtx.lock(); testValue = val; mtx.unlock(); } unsigned int getVal() { unsigned int copy = testValue; return copy; } private: boost::mutex mtx; unsigned int testValue; } ``` And my question : is above method Test::getVal() threadsafe in multithreaded environment, or it must be locked before taking copy ? I've read some articles about COW, and now I'm unsure. Thanks!