I have a boost::shared_ptr<Map>, and this map is being modified by multiple threads, do i need to use explicit mutex or just the fact that threads are modifying the map through shared pointer, i will get some sort of implicit thread safety?
2 Answers
Did you even look at the docs?
shared_ptr objects offer the same level of thread safety as built-in types. A shared_ptr instance can be "read" (accessed using only const operations) simultaneously by multiple threads. Different shared_ptr instances can be "written to" (accessed using mutable operations such as operator= or reset) simultaneosly by multiple threads (even when these instances are copies, and share the same reference count underneath.)
Any other simultaneous accesses result in undefined behavior.
Edit: It looks like you're asking about the object pointed to, not the pointer itself. There are no thread safety gaurentees at all in that case. Why would there be?
1 Comment
shared_ptr has the same level of thread safety as built-in types.
You can perform read (const) operations from multiple threads simultaneously.
You can also perform write operations (i.e. use mutable operations such as operator= or reset) on different shared_ptr instances simultaneosly from multiple threads. This includes the case when these instances share the same reference count (because shared_ptr provides atomic increment/decrement for the ref counter).
If you need any other type of access, you will need to synchronize it or otherwise you'll get undefined behavior.
shared_ptrabsolutely does not do anything for thread safety. All it does is provide reference-counting semantics around a dynamically allocated object.shared_ptrprovides is only for the pointer itself. It doesn't do anything to protect the object itself. Once you get a pointer to the underlying object out of theshared_ptrstructure, no more magic happens for you.