Is a shared pointer (std::shared_ptr) safe to use in a multi-threaded program?
I am not considering read/write accesses to the data owned by the shared pointer but rather the shared pointer itself.
I am aware that certain implementations (such as MSDN) do provide this extra guarantee; but I want to understand if this is guaranteed by the standard and as such is portable.
#include <thread>
#include <memory>
#include <iostream>
void function_to_run_thread(std::shared_ptr<int> x)
{
std::cout << x << "\n";
}
// Shared pointer goes out of scope.
// Is its destruction here guaranteed to happen only once?
// Or is this a "Data Race" situation that is UB?
int main()
{
std::thread threads[2];
{
// A new scope
// So that the shared_ptr in this scope has the
// potential to go out of scope before the threads have executed.
// So leaving the shared_ptr in the scope of the threads only.
std::shared_ptr<int> data = std::make_shared<int>(5);
// Create workers.
threads[0] = std::thread(function_to_run_thread, data);
threads[1] = std::thread(function_to_run_thread, data);
}
threads[0].join();
threads[1].join();
}
Any links to sections in the standard most welcome.
I would be happy if people have reference to the major implementations so we could consider it portable to most normal developers.
- MSDN: Check. Thread Safe.
- G++: ?
- clang: ?
I would consider those the major implementations but happy to consider others.