Search code examples
c++boostthread-safetyshared-ptratomic

Why does boost::shared_ptr use gcc inline assembly to increase use_count instead of using operator++?


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?


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.