lundi 29 juin 2015

Effect of std::memory_order_acq_rel on non-atomic variable read in other thread

I think I mostly understand the semantics of the various memory_order flags in the C++ atomic library.

However, I'm confused about the following situation:

Suppose we have two threads - Thread A, which is a "main execution" thread, and Thread B, which is some arbitrary thread that is part of a thread pool where tasks can be scheduled and run.

If I perform a "read-write-update" atomic operation using std::memory_order_acq_rel, then perform a non-atomic write on a boolean variable, is the non-atomic write immediately visible to other threads? I would think the answer is no, unless the other threads also access the atomic variable that did the "read-write-update" operation.

So, for example, given a global std::atomic_flag variable X, a global bool value B, and a thread pool object THREADPOOL that has a member function dispatch, which will execute arbitrary function handlers in another thread:

if (!X.test_and_set(std::memory_order_acq_rel)
{
   if (SOME_CONDITION) B = true;
   THREADPOOL.dispatch([]() { 
      // This executes in Thread B
      if (B) { /* do something */ } // are we guaranteed to see changes to B?
   });
}

So in this example, the code inside the lambda function will be executed in a different thread. Is that thread necessarily going to see the (non-atomic) update to B made in the first thread? Note that the second thread does not access the atomic_flag, so my understanding is that changes to B will not necessarily be seen in the second thread.

Is my understanding correct here? And if so, would using std::memory_order_seq_cst change that?

Aucun commentaire:

Enregistrer un commentaire