Say I have some class whatever nature it might have. I want to share an object of this class between threads. In the past, I would have thought that a mutex
- while it might not be the most efficient way - would be enough to make sure that everything works.
Now, I have read a bit about std::atomic
and that it is necessary even for simple bool references: Do I have to use atomic<bool> for "exit" bool variable?
While I understand why a bool should be atomic, I do not understand how a simple mutex prevents the following issue:
Second, when two threads run on different cores, they have separate caches; writing a value stores it in the cache, but doesn't update other caches, so a thread might not see a value written by another thread.
Is a mutex not merely a mechanism that makes sure that some other thread is not be able to lock the mutex? But within the mutex area I might play around with a whole bunch of variables. The compiler might not know which variables are involved.
As a consequence, simply putting a mutex-based lock around all areas that contain shared resources does not seem sufficient to me at the moment. Could it not still be that the two threads have different versions of this resource because the thread caches just will not be updated?