使用互斥锁和条件变量提升跨内存的进程间共享向量

Boost Interprocess share vector across memory with mutex and condition variable

我在网上找到这段代码 (http://prakharprakhar.blogspot.co.uk/2009/12/boost-shared-memory-vector.html),详细说明了如何通过 Boost Interprocess 共享向量:

正在共享内存中写入向量

using namespace boost::interprocess;

using ShmemAllocator = allocator<int, managed_shared_memory::segment_manager>;
using MyVector = vector<int, ShmemAllocator>

int main()
{
    shared_memory_object::remove("MySharedMemory");

    managed_shared_memory segment(create_only, "MySharedMemory", 65536);

    const ShmemAllocator alloc_inst(segment.get_segment_manager());

    MyVector* myVector = segment.construct<MyVector>("MyVector")(alloc_inst);

    for(int i = 0; i < 100; ++i)
    {
        myVector->push_back(i);
    }
}

从共享内存中的向量读取

int main()
{
    using namespace boost::interprocess;

    using ShmemAllocator = allocator<int, managed_shared_memory::segment_manager>
    using MyVector = vector<int, ShmemAllocator>;

    managed_shared_memory segment(open_only, "MySharedMemory");
    MyVector* myVector = segment.find<MyVector>("MyVector").first;

    std::cout << "Size of shared vector: " << myVector->size() << std::endl;

    MyVector::iterator iter = myVector->begin();
    while(iter++ != myVector->end())
    {
        std::cout << "nvalue = " << *iter << std::endl;
    }

    //segment.destroy<MyVector>("MyVector");
}

不过,我想同步我的两个processes/threads。我需要一个互斥锁来防止同时访问和一个条件变量来通知 reader 有数据。

从这里阅读:

https://www.boost.org/doc/libs/1_57_0/doc/html/interprocess/synchronization_mechanisms.html

我看到典型的设计是将互斥锁和条件变量放在跨内存共享的对象中。因此,我着手创建一个结构:

struct MySharedData
{
    MyVector vec;
    interprocess_mutex      mutex;
    interprocess_condition  cond_empty;
}

但是,Boost 文档示例不需要共享内存分配器,所以我不确定是否可以简单地将 MyVector 放在结构中。

我如何将自定义向量分配器与 "wrapper" 结构集成,以包含互斥锁和条件变量?

I therefore proceeded to create a struct:

struct MySharedData
{
    MyVector vec;
    interprocess_mutex      mutex;
    interprocess_condition  cond_empty;
}

看起来神志清醒。为什么会有问题?只需添加一个构造函数来初始化向量的分配器。这可能有效:

MySharedData::MySharedData(managed_shared_memory::segment_manager* sm) 
   : vec(sm) 
{}