以原子方式读取 boost shared_ptr
我有 2 个线程访问这个对象。
线程 A:更新 boost hared_ptr 成员 线程B:读取boostshared_ptr成员
由于shared_ptr不是整数/实数指针类型,因此线程B无法以原子方式读取它。
我想避免锁。
我怎样才能保证线程B获得有效的shared_ptr?
谢谢!
I have 2 threads that access this one object.
Thread A: updates a boost hared_ptr member
Thread B: reads that boost shared_ptr member
Since a shared_ptr isn't an integer/real pointer type, it cannot be read atomically by Thread B.
I want to avoid locks.
How can I guarentee that Thread B gets a valid shared_ptr?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
即使它是普通类型,也不能保证读取在现实世界中以原子方式完成,具体取决于您的架构。
还要考虑线程 B 长时间停滞的情况,并且仍然有一个指向 A 从那时起就可以删除的旧对象的指针。在这种情况下,您可能需要考虑使用 RCU 来防止 A 删除旧指针。但这也意味着更多的代码和更多难以发现的错误
只需使用锁即可。额外的开销使您不必弄清楚为什么非同步不起作用。如果您确实想避免锁,请避免使用共享变量。
Even if it was an ordinary type, there wouldn’t be a warranty that a read is done atomically in the real world depending on your architecture.
also consider the case where thread B stalls for a long time, and still have a pointer to an old object that A could have deleted since then. In that case you may want to consider using RCU to prevent A from deleting the old pointer. but that also mean more code and more hard-to-find bugs
Just use locks. The extra overhead saves yourself from having to figure out why your non-synchronisation won't work. If you really wants to avoid locks, avoid using shared variables.