Sobes.tech
Junior — Middle

Does shared_ptr ensure safety when working in a multithreaded environment?

sobes.tech AI

Answer from AI

std::shared_ptr provides safety when working with the reference counter itself in a multithreaded environment. This means that copy, assignment, and destruction operations of shared_ptr objects are thread-safe, and the reference counter is correctly updated when accessed from different threads.

However, the object pointed to by shared_ptr is not protected from concurrent access from multiple threads. If multiple threads modify the object, additional synchronization mechanisms (such as mutexes) are necessary.

Example:

#include <memory>
#include <thread>
#include <iostream>

std::shared_ptr<int> ptr = std::make_shared<int>(42);

void thread_func() {
    auto local_ptr = ptr; // safely increments the reference counter
    std::cout << *local_ptr << std::endl;
}

int main() {
    std::thread t1(thread_func);
    std::thread t2(thread_func);
    t1.join();
    t2.join();
}

Here, operations with shared_ptr are thread-safe, but if we were to modify *ptr without synchronization, it would be unsafe.