This page on Thread Safety by Microsoft says shared_ptr should be used even if there are multiple copies sharing the same object.
So does this mean that both of the following are acceptable? I've tried both and they appear to work fine.
EDIT: The actual business objective is to get string updates from the long running thread to the main thread. I figured I should use shared_ptr since string is not thread safe. Don't care about ownership honestly.
Option 1 (Passing reference):
auto status = std::make_shared<std::string>();
auto f = [&status]() {
...
*status = "current status";
...
};
std::thread t{f};
while(true) {
std::cout << *status << std::endl;
std::this_thread::sleep_for(1000ms);
if (*status == "completed") break;
}
t.join();
Option 2 (Making a copy):
auto status = std::make_shared<std::string>();
auto f = [](std::shared_ptr<std::string> s) {
...
*s= "current status";
...
};
std::thread t{f, status};
while(true) {
std::cout << *status << std::endl;
std::this_thread::sleep_for(1000ms);
if (*status == "completed") break;
}
t.join();
EDIT2: So apparently both these approaches are wrong for what I'm trying to achieve. I need to use std::mutex (cppreference) and not muck around with shared_ptr. See second half of this answer.