Data race при использовании shared_ptr
В книге Concurrency with Modern C++ автора Rainer Grimm для вот таких строчек кода:
std::shared_ptr<int> ptr = std::make_shared<int>(2011);
for (auto i=0; i<10; i++){
std::thread([&ptr]{
ptr = std::make_shared<int>(2014);
}
).detach();
}
есть утверждение:
The lambda-function binds the std::shared_ptr ptr in line 4 by reference. This means, the assignment (line 5) may become a concurrent reading and writing of the underlying resource; therefore, the program has undefined behaviour.
Скажите, почему поведение будет неопределенным? На мой взгляд это противоречит cppreference
All member functions (including copy constructor and copy assignment) can be called by multiple threads on different instances of shared_ptr without additional synchronization even if these instances are copies and share ownership of the same object.
Ответы (1 шт):
"я полагал что управляющий блок shared_ptr защищен" - именно так. Только этот защищенный управляющий блок не содержится в ptr. А операции с самим ptr не защищены.
Цитата в вопросе относится к случаю, когда доступ из разных потоков производится к ранызным экземплярам shared_ptr, которые при этом могут разделять владение одним и тем же объектом. А в коде случай, когда доступ из разных потоков производится к одному и тому же экземпляру shared_ptr:
If multiple threads of execution access the same instance of shared_ptr without synchronization and any of those accesses uses a non-const member function of shared_ptr then a data race will occur;