Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is unique_ptr thread safe?

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; } 
like image 616
Valentin Milea Avatar asked Jul 14 '12 09:07

Valentin Milea


People also ask

Do I need to delete unique_ptr?

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.

Is boost :: shared_ptr thread safe?

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.

When should we use unique_ptr?

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.

Are unique pointers thread safe?

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.


1 Answers

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!

like image 90
Bartosz Milewski Avatar answered Oct 15 '22 21:10

Bartosz Milewski