开发者

Reading a boost shared_ptr atomically

开发者 https://www.devze.com 2023-01-15 06:16 出处:网络
I have 2 threads t开发者_开发知识库hat access this one object. Thread A: updates a boost hared_ptr member

I have 2 threads t开发者_开发知识库hat 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!


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消