Search code examples
corder-of-execution

Force memory ordering


If there are pointers "A" and "B", with a requirement such that any writes to "A" should be made visible before any writes to "B" are made visible. If I am not allowed to use locks and if I am not allowed to declare these variables as "volatile", will the following code guarantee that, the above requirement will be met?

volatile temp;

*A = value1;
temp = *A;

if (temp == value1) {
    *B = value2
}

Solution

  • You will want to use memory barriers or fences: see http://en.wikipedia.org/wiki/Memory_barrier

    In the Linux kernel you can use the rmb() or wmb() calls.

    Under pthreads you can use pthread_barrier_wait(), though that doesn't appear to be in my pthreads manpages.

    On MSVC, look at Force order of execution of C statements? - which also has some good general information.

    If you find an 'atomic' library, that will normally include barrier functions.