dimanche 29 mars 2015

C++11 Multithreading Data Protection Semantics

In the following code:



class SomeClass
{
private:
static SomeType sharedvar;
std::mutex Mutex;
public:
void DoStuff()
{
Mutex.lock();
//do stuff with sharedvar
Mutex.unlock();
}
}


is it guaranteed that the changes to sharedvar will actually be stored when Mutex.unlock() is called, and not simply kept in the CPU's cache? I read about a similar example with a global variable, and it explained that this behavior occurs because the compiler can't know if a function implemented in an external library accesses the global variable, so the variable has to be kept up to date before each call to that function. However, in this example, sharedvar is private and can only be accessed by functions declared in SomeClass, which the compiler can see and make assumptions about. If sharedvar is updated when Mutex.unlock() is called, how/why does this this behavior occur (please explain in detail)? If it isn't, what can I do to fix it (would I need volatile)? I also had the crazy idea of declaring std::mutex::lock as a friend function, in order to reintroduce the uncertainty that (I think) makes the example above work.


Aucun commentaire:

Enregistrer un commentaire