문제

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

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top