Boost logo

Boost :

Subject: [boost] [Atomic] Confusion about Atomicaty of atomic::exchange.
From: cexer (cexer_at_[hidden])
Date: 2010-09-27 05:23:21


Hey guys, I am very interested in Boost.Atomic library, but when I went deeply into the source code, I found there are mysteries that I can not fullly understand, for example, the implementation of atomic::exchange, list its implementation code (see. /atomic/builderhpp, line 47.) as follow :

    integral_type exchange(integral_type replacement, memory_order order=memory_order_seq_cst) volatile
    {
        integral_type o=load(memory_order_relaxed); // A
        do {} while(!compare_exchange_weak(o, replacement, order, memory_order_relaxed)); // B
        return o;
    }

From my view, although atomic::load and atomic::compare_exchnage_weak are both atomic operations, the atomicity of atomic::exchnage is not guaranteed,take this illustrative code-snippet for example :

    atomic<int> i( 1 );
    thread1 i.exchange( 100 );
    thread2 i.exchange( 200 ); // C

To help explanation, in the atomic::exchange method and the above code-snippet, I lable corresponding code fragments as A, B, C.

Assume that thread1 is completed running A, but has not arrive B yet, at this moment values of i and o ( o is the temporary variable in atomic::exchange method, see source code of atomic::exchnage above. ) are:

    o == 1
    i == 1

Since the atomic::exchange is not locked, and calling to atomic::load using memory order of memory_order_relaxed, under this circumstance, atomic::exchnage is not prevent from calling from more than one threads, so these is possibility that thread2 could call atomic::exchange (like the code C above) between A and B, after thread2 completed C, the value of i is changed, values of i and o values are now:

    o == 1
    i == 200
    
Then thread1 arrives code B, because at this moment o! = i, calling to compare_exchnage_weak will fail, atomic::exchange them will went into infinite loop, this is terrible. I know I must missing something here, so I posting here, expecting that someone could please remind me a little bit?


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk