std::shared_ptr<int> int_ptr;
int main() {
int_ptr = std::make_shared<int>(1);
std::thread th{[&]() {
std::weak_ptr int_ptr_weak = int_ptr;
auto int_ptr_local = int_ptr_weak.lock();
if (int_ptr_local) {
cout << "Value in the shared_ptr is " << *int_ptr_local << endl;
}
});
int_ptr.reset(nullptr);
th.join();
return 0;
}
上面的代码是线程安全的吗?我看了这篇回答 关于 weak_ptr 的线程安全性,但我只想确保上面的代码是线程安全的。
我问这个问题的原因是,如果上述代码确实是线程安全的,我就无法理解为什么 std::weak_ptr 和 std::shared_ptr 接口会使以下操作具有原子性 expired() ? shared_ptr<T>() : shared_ptr<T>(*this)。在我看来,像上面那样进行两行逻辑代码同步执行的操作似乎是不可能的,除非使用某种互斥体或自旋锁。
我理解如何通过不同 shared_ptr 实例的原子增量工作,我也理解 shared_ptr 本身不是线程安全的,但如果上面的内容确实是线程安全的,它就非常像一种线程安全的 shared_ptr,我不明白像上面的条件语句中的两行代码如何在没有锁的情况下做到原子化。
shared_ptr
” - 使用共享的shared_ptr
来构造weak_ptr
真的是线程安全的吗? - Holt