1

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? .

Community
  • 1
  • 1
Benito Ciaro
  • 1,718
  • 12
  • 25
  • 1
    Also note that concurrent execution of `f` will cause data races. Mutexes are not supposed to be used only for the write accesses (who gave you that idea?). – R. Martinho Fernandes Jan 10 '13 at 12:39

1 Answers1

2

Acquiring a mutex synchronizes with releasing the mutex. That means that whenever you acquire a mutex, you can observe every side-effect that is sequenced before the mutex was released. The implementation is free to implement that however it wants. What matters is that the effects are these.

R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510