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

StackOverflow https://stackoverflow.com/questions/11532970

سؤال

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?

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top