Home > Software engineering >  Is shared pointer thread-safety zero-cost?
Is shared pointer thread-safety zero-cost?

Time:08-17

I recently found out that the control block for shared pointers (the thing that manages the reference count) is thread-safe, so things like copying and passing shared pointers are safe for multithreaded uses. However, I also know that one of the ideals of C is that you shouldn't have to pay for features you don't use. To me, it seems that the thread-safety of the control block would require some mutex locks, which is some overhead.

Given that it is perfectly reasonable to use shared pointers in non-multithreaded applications, I don't see why this overhead is accepted. So my question is whether the C language designers decided to take the bullet and accept this additional overhead for all cases, or if this thread-safe control block can be implemented in a way that it is zero-cost (unlike my naive mutex lock assumption).

CodePudding user response:

No, std::shared_ptr's thread-safety is not zero-cost.

The alternative, however, would be a shared_ptr that is essentially unusable in a multithreaded environment. It would be impossible for multiple threads to safely hold multiple shared_ptrs to the same object without the possibility of creating data races on the control block.

To solve that problem, the standard library would need separate thread-safe and non-thread-safe shared_ptr types, which would significantly complicate the interfaces of anything that uses std::shared_ptr. I assume this complication was deemed to outweigh the fairly minimal overhead of simply always performing atomic updates on the control block's reference counts.

  • Related