Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 308
amazingjxq Avatar asked Mar 04 '26 14:03

amazingjxq


2 Answers

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.

like image 139
timos Avatar answered Mar 07 '26 04:03

timos


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.

like image 20
Hrishi Avatar answered Mar 07 '26 03:03

Hrishi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!