Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is std::shared_ptr using atomic cpu operations

I have a problem understanding why shared_ptr is using atomic cpu instructions... I cant figure out the reasons because it is NOT thread safe. Can somebody please explain.

If you wonder know how I know that it uses atomic intstuructions: there was a clip from C++ and beyond where Herb and Andrei talk about it, but they never mention the reasons why is it like that.

like image 518
NoSenseEtAl Avatar asked Jan 23 '12 23:01

NoSenseEtAl


2 Answers

Any instance of shared_ptr is multi-thread safe. The data it points to is not multi-thread safe. See this.

The atomic instructions, if properly applied (protection done in the same order by competing thread access) is one way to implement thread safety. Another way is by use of mutexes.

See a similar question for BOOST: Is boost shared_ptr xxx thread safe?

like image 140
wallyk Avatar answered Nov 09 '22 08:11

wallyk


Herb Sutter just used shared_ptr as a nice example in his gotw 95, he goes there to elaborate on design decision:
https://herbsutter.com/2014/01/13/gotw-95-solution-thread-safety-and-synchronization/

like image 35
NoSenseEtAl Avatar answered Nov 09 '22 06:11

NoSenseEtAl