std::shared_ptr<Dog> pd;
void F() {
pd = std::make_shared<Dog>("Smokey");
}
int main() {
std::thread t1(F);
std::thread t2(F);
t1.join();
t2.join();
return 0;
}
std::shared_ptr<Dog> pd(new Dog("Gunner"));
void F() {
std::shared_ptr<Dog> localCopy = pd;
}
int main() {
std::thread t1(F);
std::thread t2(F);
t1.join();
t2.join();
return 0;
}
In C++, I understand that std::shared_ptr is thread-safe for reading and copying. But I'm a little confused about when I need to use a mutex to synchronize threads. I have two code snippets. In the first one, std::shared_ptr is being modified by multiple threads. In the second one, each thread is only reading from and copying the shared pointer. Do I need a mutex in both situations, or just in the first one? Why or why not?"
std::shared_ptrvariable is no more thread safe than any other type of variable. If more than one thread accesses (reads or writes) the variable, and if at least one of them writes the variable, then all of those accesses must be "synchronized." One way to synchronize is for all of them to have the same mutex locked whenever they access the variable.