Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What C++11 <atomic> operations/memory orders guarantees freshness? [duplicate]

Possible Duplicate:
Concurrency: Atomic and volatile in C++11 memory model

With the C++11 <atomic> specification, is there any guarantee of freshness? The descriptions of different memory orders only deal with reorderings (as far as I've seen).

Specifically, in this situation:

#include <atomic>

std::atomic<int> cancel_work(0);

// Thread 1 is executing this function
void thread1_func() {

    ...

    while (cancel_work.load(<some memory order>) == 0) {
        ...do work...
    }
}


// Thread 2 executes this function
void thread2_func() {

    ...

    cancel_work.store(1, <some memory order>);

    ...

}

If thread 1 and thread 2 do not share any other data except cancel_work, it seems to me that any ordering guarantees are not needed and std::memory_order_relax suffices for both the store and the load. But does this guarantee that thread 1 will ever see the update of cancel_work instead of just repeatedly reading its local cache line without ever refreshing it from main memory? If not, what is the minimum needed to make that guarantee?

like image 554
JanKanis Avatar asked Feb 04 '13 13:02

JanKanis


People also ask

What is memory model in C ++ 11?

C++11 Memory Model. A memory model, a.k.a memory consistency model, is a specification of the allowed behavior of multithreaded programs executing with shared memory [1].

What is an atomic memory operation?

An operation acting on shared memory is atomic if it completes in a single step relative to other threads. When an atomic store is performed on a shared variable, no other thread can observe the modification half-complete.

What is memory order in c++?

(since C++20) std::memory_order specifies how memory accesses, including regular, non-atomic memory accesses, are to be ordered around an atomic operation.

Is volatile atomic in C?

In C and C++Operations on volatile variables are not atomic, nor do they establish a proper happens-before relationship for threading.


1 Answers

There is nothing that will guarantee that: everything is about ordering. Even memory_order_seq_cst just guarantees that things happen in a single total order. In theory, the compiler/library/cpu could schedule every load from cancel_store at the end of the program.

There is a general statement in 29.3p13 that

Implementations should make atomic stores visible to atomic loads within a reasonable amount of time.

But there is no specification on what constitutes a "reasonable amount of time".

So: memory_order_relaxed should be just fine, but memory_order_seq_cst may work better on some platforms, as the cache line may be reloaded sooner.

like image 117
Anthony Williams Avatar answered Oct 14 '22 16:10

Anthony Williams