11

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.

ildjarn
  • 62,044
  • 9
  • 127
  • 211
NoSenseEtAl
  • 28,205
  • 28
  • 128
  • 277

2 Answers2

15

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?

Community
  • 1
  • 1
wallyk
  • 56,922
  • 16
  • 83
  • 148
  • 6
    To be more specific: the shared reference count inside `shared_ptr` may be accessed by multiple threads. That's why it's necessary to increment/decrement it atomically. – Bartosz Milewski Jan 24 '12 at 23:58
  • This answer is a bit misleading; `shared_ptr` operations are not atomic, so writing to the same shared_ptr instance from one thread while reading from it in another thread is not in fact safe. The control block is the only thread-safe part of shared_ptr. – rdb May 23 '18 at 10:08
2

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/

johnchen902
  • 9,531
  • 1
  • 27
  • 69
NoSenseEtAl
  • 28,205
  • 28
  • 128
  • 277
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. (And I'm too lazy to do the job) – johnchen902 Sep 07 '17 at 17:23