[英]no crash if I reset the same shared_ptr in multi-threads
我只想确认在多线程中使用锁定重置为相同的智能指针是安全的吗? 如果没有lock_guard,它不安全,因为它不是线程安全的方法? 我想重置不是线程安全的,但是,如果我删除了锁,则不会观察到崩溃。
class foo {
public:
foo()
{
std::cout << "foo constructed" << std::endl;
}
~foo()
{
std::cout << "foo destructed" << std::endl;
}
};
int main(int argc, const char * argv[]) {
std::shared_ptr<foo> f = std::make_shared<foo>();
conqueue = dispatch_queue_create("MyConcurrentDiapatchQueue", DISPATCH_QUEUE_CONCURRENT);
static std::mutex io_mutex;
for (int i = 0; i < 100000; i++)
{
dispatch_async(conqueue, ^{
std::lock_guard<std::mutex> lk(io_mutex); // no crash without this line as well
f.reset(); // it's safe? No crash if I reset the same shared_ptr in multi-threads.
});
}
return 0;
}
shared_ptr
对象不是线程安全的,指向的对象也不是线程安全的。 只有引用计数是线程安全的。 所以是的,你需要使用警卫。
在 C++20 中,有std::atomic<std::shared_ptr<T>>
。
文档不能保证该组件的安全性。 基本上,如果标准对此一无所知,那么您的假设是正确的。 你必须有那个 lockquard 或任何提供相同功能的东西。
崩溃可能是不可观察的,因为在尝试在并发线程中读取指针之前您没有竞争条件,因为您实际上并没有尝试使用该值(reset 所做的只是更改指针值)。
好吧,你不能依赖于你不能观察到 UB,UB 是一只薛定谔的猫。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.