Sobes.tech
Middle

Is shared_ptr thread-safe and can it be used in a multi-threaded context?

sobes.tech AI

Answer from AI

Yes, shared_ptr is thread-safe for increment/decrement operations on the reference counter. This means that multiple threads can simultaneously copy or destroy a shared_ptr to the same resource without data races on the counter.

However, access to the managed data object through multiple shared_ptrs from different threads is not thread-safe by default. If different threads read and/or modify this object simultaneously, you need to use additional synchronization mechanisms (e.g., mutexes) to protect the object itself.

Using shared_ptr in a multithreaded context is possible and often necessary, but it requires understanding which part of shared_ptr (the counter) is thread-safe and which (access to data) is not.

#include <iostream>
#include <memory>
#include <thread>
#include <vector>
#include <mutex> // For synchronizing access to data

struct Data {
    int value;
    std::mutex mutex; // Mutex to protect value

    Data(int v) : value(v) {}
};

int main() {
    auto shared_data = std::make_shared<Data>(0);

    auto increment = [&](std::shared_ptr<Data> ptr) {
        // Accessible from different threads - reference counter is thread-safe
        std::lock_guard<std::mutex> lock(ptr->mutex); // Protect access to value
        ptr->value++;
    };

    std::vector<std::thread> threads;
    int num_threads = 10;

    for (int i = 0; i < num_threads; ++i) {
        threads.emplace_back(increment, shared_data); // Passing a copy of shared_ptr
    }

    for (auto& t : threads) {
        t.join();
    }

    std::cout << "Final value: " << shared_data->value << std::endl; // Should be 10

    return 0;
}