shared_ptr<int> p(new int(42));
//--- My Example ---
// thread A
p.reset(new int(1912));
// thread B
shared_ptr<int> p1 = p;
So my question is whether the last example is OK or not?
NOTE: Boost's third example explains that it is not safe to read and write the same object in parallel. But in their example they assign p3
to p
, which is a copy of p3
. So it is not clear to me whether the safety of that example depends on the fact that p3
gets assigned to its copy or whether something else is unsafe.
–
–
–
But they does not say (or I cannot see) what will happen if the same shared_ptr object will be written and read at the same time.
Yes they do:
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
) simultaneously by multiple threads (even when these instances are copies, and share the same reference count underneath.)
Any other simultaneous accesses result in undefined behavior.
(emphasis mine)
Seems pretty clear to me.
So my question is whether the last example OK or not?
No, because what you are doing is not reading simultaneously from a single instance, nor writing to separate instances. You are simultaneously reading and writing a single instance. That's a data race, and undefined behaviour.
Now that we have C++11 (and 14/17), you may use the atomic shared pointer classes to atomically handle shared pointers in your threads.
http://en.cppreference.com/w/cpp/memory/shared_ptr/atomic
Simply put, if you may end up modifying a shared pointer, you should use the atomic functions everywhere (all reads and all writes.) Then your threads should not crash because of the shared pointer.
–
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.