samedi 22 août 2020

Can mutex in C++ guarantee the visibility of atomic operations?

According to C++ Reference, mutex.lock() is a memory_order_acquire operation, and mutex.unlock() is a memory_order_release operation.

However, memory_order_acquire and memory_order_release are only effective for non-atomic and relaxed atomic operations.

Could mutex in C++ guarantee the visibility of atomic operations? An example is as follows. Can the code A reorder before the mu.lock(), and the thread b read x as false?


#include <thread>
#include <atomic>
#include <cassert>
#include <iostream>
#include <unistd.h>

std::atomic<bool> x = {false};
std::mutex mu;

void write_x(){
  mu.lock();
  std::cout << "write_x" << std::endl;
  x.store(true, std::memory_order_release);
  mu.unlock();
}

void read_x() {
  mu.lock();
  std::cout << "read_x" << std::endl;
  assert(x.load(std::memory_order_acquire)); // A
  mu.unlock();
}

int main() {
  std::thread a(write_x);
  usleep(1);
  std::thread b(read_x);

  a.join(); b.join();

  return 0;
}

Aucun commentaire:

Enregistrer un commentaire