Given threads TA and TB contending in f() below:
struct C {
C(): a(0) {}
int a;
std::mutex mtx;
void f() {
... // use 'a' in readonly mode
std::lock_guard<std::mutex> lock(mtx); // assume TA gets the lock first, then TB
a += 2; // what value of 'a' will TB see?
}
}
how does TB know, upon acquiring the lock, that his cached copy of 'a' is stale?
This is how people have programmed for ages without explicitly using atomics or memory barriers, and it all works fine. Does acquiring a mutex (or spinlock) issue an implicit memory barrier? Thanks.
EDIT: Maybe this is a dup of Are mutex lock functions sufficient without volatile? .