为什么创建一个由不同进程共享的环形缓冲区如此困难(在 C++ 中),我做错了什么?

发布于 2024-08-24 10:04:36 字数 1606 浏览 9 评论 0原文

我对此特别敏感,但似乎我错过了一个重要的基本点或其他东西,因为我想做的事情应该是常见的:

我需要从管理器进程创建一个固定大小的环形缓冲区对象(<代码>处理M)。该对象具有用于从缓冲区写入/读取的 write()read() 方法。读/写方法将由独立进程调用(Process RW

我已经实现了缓冲区,SharedBuffer ,它使用 boost::interprocess 在 SHM 中分配缓冲区槽,并在单个进程内完美工作。我已阅读这个问题那个 on SO,以及询问我自己的,但我仍然不知道如何有不同的进程从公共对象访问方法。 Boost 文档有一个示例 在SHM中创建一个向量,这与我想要的非常相似,但我想实例化我自己的类。

我当前的选择是:

  1. 使用放置 new,按照 Charles B. 的建议 我的问题;不过,他警告说,将非 POD 对象放入 SHM 中并不是一个好主意。但我的类需要读/写方法,我该如何处理这些方法?
  2. 将分配器添加到我的类定义中,例如具有 SharedBuffer 并以类似于 向量示例在boost中给出。这听起来确实很复杂。
  3. SharedBuffer 更改为 POD 类,即删除所有方法。那么进程间的读写如何同步呢?

我缺少什么?固定长度的环形缓冲区非常常见,因此这个问题要么有解决方案,要么我做错了什么。

I am being especially dense about this but it seems I'm missing an important, basic point or something, since what I want to do should be common:

I need to create a fixed-size ring buffer object from a manager process (Process M). This object has write() and read() methods to write/read from the buffer. The read/write methods will be called by independent processes (Process R and W)

I have implemented the buffer, SharedBuffer<T&>, it allocates buffer slots in SHM using boost::interprocess and works perfectly within a single process. I have read the answers to this question and that one on SO, as well as asked my own, but I'm still in the dark about how to have different processes access methods from a common object. The Boost doc has an example of creating a vector in SHM, which is very similar to what I want, but I want to instantiate my own class.

My current options are:

  1. Use placement new, as suggested by Charles B. to my question; however, he cautions that it's not a good idea to put non-POD objects in SHM. But my class needs the read/write methods, how can I handle those?
  2. Add an allocator to my class definition, e.g. have SharedBuffer<T&, Alloc> and proceed similarly to the vector example given in boost. This sounds really complicated.
  3. Change SharedBuffer to a POD class, i.e. get rid of all the methods. But then how to synchronize reading and writing between processes?

What am I missing? Fixed-length ring buffers are very common, so either this problem has a solution or else I'm doing something wrong.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

东北女汉子 2024-08-31 10:04:36

环形缓冲区在这里不是问题,使用共享内存才是问题。解决方案是使用placement new 来分配对象,或者至少分配它的内部缓冲区。仅仅拥有成员函数、构造函数和析构函数不会造成麻烦,但请确保您不使用虚函数或包含非 POD 对象,因为这可能会变得棘手。

The ring buffer is not a problem here, using shared memory is. The solution to that is using placement new for allocating your object, or at least for allocation of an internal buffer of it. Simply having member functions, constructors and destructors shouldn't cause trouble, but make sure that you do not use virtual functions or contain non-POD objects, as that may get tricky.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文