I’m getting a bit confused with the new threading in C++11. I get how I can use mutexes to stop two threads from operating on the same data at the same time, but what about assigning to that data?
Example!
class Foo
{
std::string s;
// This would be called on a seperate thread
void Bar() { s = std::string( "blah blah blah" ); }
};
So what I’m asking is, because I’m assigning something to s, does the member variable s always stay in the same memory location, and assignments just change the internal data, in which case I just need a mutex? Or can I still get into situations with cached values and things which mean I need to start using atomic<> to make sure I have the up to date data? Or is that just for types like ints, or structs?
Mutexes are guaranteed sufficient. Whatever magic is needed to make it work, they contain. So long as every thread that accesses or modifies any particular instance of
sdoes so under protection of the same mutex, there will be no issue.The only difference between access and assignment is this — you do not need a mutex to prevent two threads from reading the same data at the same time. A mutex is only required when an object may be modified in one thread while another thread is or might be accessing it. Concurrent reads are permitted.
Note that this is the usual rule and applies to typical objects like
std::string. One can, if one wishes to, make an object that breaks even with concurrent reads and even when one object is read in one thread while a different object of the same type is read in another thread. (But such objects are not useful and people just shouldn’t make them.)