unique_ptr 的侵入性列表?
我有一个高度多线程的程序,它包含一个侵入性的对象链接列表。我需要将此列表中的对象传递给多个线程,但一次只有 1 个线程拥有该对象,这意味着我不需要共享该对象或指向它的指针。
我想使用 boost 创建一个带有 unique_ptr 的侵入式列表,但从我读到的内容来看,unique_ptr 与 Boost 侵入式库不兼容,因为它没有正确的所有权语义。
根据此侵入式库要求它的元素(指针)具有与原始指针相同的所有权语义。所以unique_ptr甚至shared_ptr都不符合资格。
我想知道是否有人可以给我一些关于如何最好地实现我的侵入式列表的建议,这样我就可以安全地通过多个线程传递它的元素,并知道它们被移动到该线程而不是在线程之间共享?
I have a program that is highly multi-threaded and it contains an intrusive linked list of objects. I need to pass off the objects in this list to several threads, but only 1 thread will ever own the object at a time, meaning that I don't need this object or the pointer to it be shared.
I wanted to create an intrusive list with a unique_ptr using boost, but from what I've read the unique_ptr would not be compatible with the Boost intrusive library as it does not have the right ownership semantics.
Per this the intrusive library requires it's elements (pointers) to have the same ownership semantics as a raw pointer. So unique_ptr or even shared_ptr would not qualify.
I wondered if anyone could give me some advice on how to best implement my intrusive list then so I can safely pass its elements through several threads and know that they are being MOVED to that thread and NOT shared amongst threads?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
据我所知,要实现此功能,您将需要某种 自动取消链接挂钩。
由于侵入式容器不拥有它所包含的对象,因此将 unique_ptrs 引用的原始指针添加到侵入式容器中应该不会有任何问题。
如果您需要能够从侵入列表中的原始指针访问实际的 unique_ptr ,请执行以下操作 enable_shared_from_this 可能会有所帮助。 (您需要将侵入式容器与侵入式 unique_ptr 结合起来。)
稍微考虑一下,似乎确实不存在侵入式 unique_ptr 变体,因为智能指针的“侵入式”部分通常是针对引用计数,和unique_ptr之类的对象没有引用计数。
也许你最好使用shared_ptr来实现这一点,因为它已经启用了enabled_shared_from_this。
As far as I follow, for this to work you will need some kind of auto-unlink hooks.
Since the intrusive container does not own the objects it contains, you should not have any problem adding the raw pointers your unique_ptrs refer to, to the intrusive container.
If you need to be able to access the actual unique_ptr from the raw pointer in the intrusive list, something along the lines of enable_shared_from_this might help. (You'd need to combine your intrusive container with an intrusive unique_ptr.)
After thinking about it a bit it seems that there really isn't an intrusive unique_ptr variant out there, since the "intrusive" part for smart pointers usually is for the reference count, and unique_ptr like objects do not have a reference count.
Probably you would be best of using shared_ptr for this, since it already has enabled_shared_from_this.