Junior — Middle
What type of smart pointer do you use to ensure safety when working with multithreading?
sobes.tech AI
Answer from AI
To ensure safety when working with multithreaded operations in C++, the smart pointer std::shared_ptr is often used. It implements reference counting with atomic operations, allowing safe sharing of object ownership between threads. Unlike std::unique_ptr, which is not thread-safe when copying, std::shared_ptr guarantees correct management of the object's lifetime in a multithreaded environment.
Example of using std::shared_ptr in a multithreaded context:
#include <iostream>
#include <memory>
#include <thread>
void threadFunc(std::shared_ptr<int> ptr) {
std::cout << "Value: " << *ptr << std::endl;
}
int main() {
auto sp = std::make_shared<int>(42);
std::thread t1(threadFunc, sp);
std::thread t2(threadFunc, sp);
t1.join();
t2.join();
return 0;
}
Here, std::shared_ptr is safely passed between threads, and the object will be destroyed only after all references are destroyed.