user2404835
user2404835

Reputation: 35

Boost memory_order_consume Example

I was looking at a Boost example regarding atomic operations and the happens-before relationship, and I'm a bit confused. In the "happens-before through release and consume" section, there is the following example that they say it is erroneous, but I cannot see it :

atomic<int> a(0);
complex_data_structure data[2];

thread1:

      data[1] = ...; /* A */
      a.store(1, memory_order_release);

thread2:

      int index = a.load(memory_order_consume);
      complex_data_structure tmp;
      if (index == 0)
          tmp = data[0];
      else
          tmp = data[1];

Boost Example

Here is what I understood (please correct me if I am wrong):

  1. If the load operation by thread2 precedes the store operation by thread1, then tmp will be data[0].
  2. If the store operation operation by thread1 precedes the load operation by thread2, then tmp will be data[ 1 ] because the store(1,memory_order_release) by thread1 will ensure that all prior writes to other memory locations are visible to thread2 even though data[] is not computationally-dependent on index.

Can somebody please clarify the error they're talking about?

Upvotes: 2

Views: 350

Answers (1)

hmjd
hmjd

Reputation: 121961

With release/consume, writes to variables prior to the store(release) are only guaranteed to be visible at the matching load(consume) if, and only if, the variables are dependent on the variable used in the store(release)-load(consume) pair.

By using int literals to index the data[] this dependency has been broken, thus writes to data[] are not guaranteed to be visible after the a.load(consume).

Upvotes: 1

Related Questions