According to cppref, accessing const
members of shared_ptr
across multiple threads is safe. But is this statement valid when we have a weak_ptr
that corresponds to a shared_ptr
?
As an example assume the following code:
#include <memory>
#include <iostream>
#include <thread>
std::shared_ptr<int> sp;
std::weak_ptr<int> gw;
int main()
{
sp = std::make_shared<int>(42);
gw = sp;
auto th1 = std::thread([]{
for (int i = 0; i < 200; i++) {
if (sp.use_count() > 1) {
std::cout << i << "\n";
std::this_thread::yield();
}
}
});
auto th2 = std::thread([]{
for (int i = 0; i < 20; i++) {
if (auto l = gw.lock()) {
std::cout << "locked ->" << l.use_count() << "\n";
std::this_thread::yield();
}
}
});
th1.join();
th2.join();
}
This code creates 2 threads. One checks use_count()
of shared_ptr()
which is a const
method and the other one use lock()
to lock weak_ptr()
which also is a const
method too. But in reality, when I call lock
on weak_ptr
, I practically increase reference count of shared_ptr
which is not thread safe unless reference count is internally guarded. I wonder if I will have a data race in situations like this. Is this supposed to be thread-safe by standard?
Yes. The reference counter is atomic, so there are no data races in your example.
That being said, mutable operations on objects pointed by std::shared_ptr
are not atomic, so they must be guarded as you would guard access via a plain pointer.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.