jeudi 25 janvier 2018

Is std::future::wait a memory barrier? (I can not explain this data race)

Here is the code:

  std::vector<bool> a(req_count_);
  std::vector<std::future<void>> waits(req_count_);

  for (int i = 0; i < req_count_; i++) {
    waits[i] = framework::Async([i, &a, this] { // send into a threadpool implementation
      a[i] = true; // write true
    });
  }

  for (int i = 0; i < req_count_; i++) {
    waits[i].wait(); // memory barrier?
  }

  int last_req_count = req_count_;
  req_count_ = 0;

  for (int i = 0; i < last_req_count; i++) {
    if (!a[i]) { // read false
      return false;
    }
  }

My question is does std::future::wait serves as a memory barrier? std::future::wait wait for the function call to complete, but does the function happens before std::future::wait (e.g., does the state mutation caused by the function call visible from other threads)?

Please correct me if you think my understanding of memory barrier is wrong.

Aucun commentaire:

Enregistrer un commentaire