Is unique_ptr thread safe? Is it impossible for the code below to print same number twice?
#include <memory> #include <string> #include <thread> #include <cstdio> using namespace std; int main() { unique_ptr<int> work; thread t1([&] { while (true) { const unique_ptr<int> localWork = move(work); if (localWork) printf("thread1: %d\n", *localWork); this_thread::yield(); } }); thread t2([&] { while (true) { const unique_ptr<int> localWork = move(work); if (localWork) printf("thread2: %d\n", *localWork); this_thread::yield(); } }); for (int i = 0; ; i++) { work.reset(new int(i)); while (work) this_thread::yield(); } return 0; }
An explicit delete for a unique_ptr would be reset() . But do remember that unique_ptr are there so that you don't have to manage directly the memory they hold. That is, you should know that a unique_ptr will safely delete its underlying raw pointer once it goes out of scope.
boost::shared_ptr<> offers a certain level of thread safety. The reference count is manipulated in a thread safe manner (unless you configure boost to disable threading support). So you can copy a shared_ptr around and the ref_count is maintained correctly.
Use unique_ptr when you want to have single ownership(Exclusive) of the resource. Only one unique_ptr can point to one resource. Since there can be one unique_ptr for single resource its not possible to copy one unique_ptr to another. A shared_ptr is a container for raw pointers.
Thread safetystd::unique_ptr is not thread safe. If one calls e.g. std::move in the two threads at the same time, one can get two pointers of the same object.
unique_ptr is thread safe when used correctly. You broke the unwritten rule: Thou shalt never pass unique_ptr between threads by reference.
The philosophy behind unique_ptr is that it has a single (unique) owner at all times. Because of that, you can always pass it safely between threads without synchronization -- but you have to pass it by value, not by reference. Once you create aliases to a unique_ptr, you lose the uniqueness property and all bets are off. Unfortunately C++ can't guarantee uniqueness, so you are left with a convention that you have to follow religiously. Don't create aliases to a unique_ptr!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With