Frage

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

War es hilfreich?

Lösung

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top