Search code examples
cmultithreadinggccatomicbuilt-in

What does __ATOMIC_RELAXED mean?


In GCC atomic built-in I found that __atomic_exchange function does have a third parameter int memorder, which could take one of the values __ATOMIC_RELAXED, __ATOMIC_SEQ_CST, __ATOMIC_ACQUIRE, __ATOMIC_RELEASE, and __ATOMIC_ACQ_REL.

__ATOMIC_RELAXED: Implies no inter-thread ordering constraints.

I am not sure how can that happen, isn't this supposed to be atomic operation and therefore there will not be any inter-thread ordering ?


Solution

  • All these builtins correspond to new C11 standard atomicity features. Standard contains perfect explanation of memory_order_relaxed ordering model and some examples (refer to 7.17.3/14)

    // Thread 1:
    r1 = atomic_load_explicit(&y, memory_order_relaxed);
    atomic_store_explicit(&x, r1, memory_order_relaxed);
    
    // Thread 2:
    r2 = atomic_load_explicit(&x, memory_order_relaxed);
    atomic_store_explicit(&y, 42, memory_order_relaxed);
    

    This code is allowed to produce r1 == 42 && r2 == 42. because store of y in thread 2 might reordered before load of r2.