我实际上是在尝试提高C++中的线程,进程和共享内存的使用率,但实际上我一直停留在进程间通信上。
我决定使用消息队列,因为我已经在过去的项目中使用过某些消息,但是从未使用过多个进程。
这是我的问题,我无法从其他进程获取注册事件。我认为在共享内存段中初始化消息队列可以解决该问题,但是我无法弄清楚如何“强制”类的新实例进入共享内存段
因为我从C++中的共享内存开始,所以我使用boost Simple Exemple
理想情况下,我希望拥有的是:
int main (void)
{
shared_memory_object shm (open_or_create, "MySharedMemory", read_write);
// initialise shm using boost Simple Exemple
shmPtr = region.get_address();
// initialise message queue named msgQueue in my shared memory segment
msgQueuePtr = &msgQueue;
}
最后,shmPtr等于msgQueuePtr。
任何帮助将不胜感激。
最佳答案
我将使用托管内存段,以便您可以“仅”在共享内存中构造类型(请注意:确保它们是POD或采用共享内存分配器来正确处理任何动态分配/引用)。
#include <boost/interprocess/managed_shared_memory.hpp>
#include <iostream>
struct MyQueue { /* */ };
namespace bip = boost::interprocess;
int main() {
bip::managed_shared_memory msm(bip::open_or_create, "test", 10ul<<30); // 10 MiB
MyQueue& q = *msm.find_or_construct<MyQueue>("queue_instance")();
}
这是一个更大的演示,其中包含队列实现+锁定等。Boost shared memory and synchronized queue issue/crash in consumer process
奖金
Boost Interprocess具有完整的message_queue实现:https://www.boost.org/doc/libs/1_73_0/doc/html/boost/interprocess/message_queue.html
因此,如果有疑问,我建议使用它。
关于c++ - 共享内存段C++中类的新实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61683761/