Search code examples
c++multithreadingpointersshared

C++ shared_ptr how to ensure thread safety?


all: According to this page c++ implementations typically uses atomic ref count to ensure thread safety, but this seems buggy in some cases.

```

void func2(shared_ptr<int>* x) {
  shared_ptr<int> a(*x);
  *a += 1;
}

thread func1() {
 shared_ptr<int> a1(new int(10));
 thread t (func2, &a1);
 return t;
}

```

As the above code shows, if the copy construction in func2 happens after the internal reference count of a1 decreases, the pointer will get deleted twice, right?


Solution

  • An atomic reference count assures that only the reference counting is thread safe. It doesn't turn the referenced class into a thread safe class. It doesn't prevent you from writing thread-unsafe code, like passing a pointer to a std::shared_ptr to a new thread, but destroying it before the new thread has an opportunity to acquire its own copy of it.

    You are still responsible for writing thread-safe logic. But you can rely on reference counting being thread-safe.