Question

I'm reading boost::shared_ptr source code and found it using this function to increase shared_ptr's use count(reference count):

inline void atomic_increment( int * pw )
{
    //atomic_exchange_and_add( pw, 1 );

    __asm__
    (
        "lock\n\t"
        "incl %0":
        "=m"( *pw ): // output (%0)
        "m"( *pw ): // input (%1)
        "cc" // clobbers
    );
}

Why not simply use the operator++ to do this? Does this give better performance?

Was it helpful?

Solution

The ++ operator reads it's operand's current value, adds 1 and writes the result back. This can be three interruptible (i.e., by another thread) steps. If two threads do this at the same time it is possible that the result is wrong. To protect against this one must use atomic operations or locks. This is done by the asm code shown above.

OTHER TIPS

The C++ standard does not guarantee the i++ or ++i operations to be atomic. So depending on compiler it may or may not be atomic. This workaround uses assembly language to get around this limitation. Now, the C++ standard includes std::atomic<T> that guarantees the operations on the object to be atomic.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top