我在网上发现了这段代码(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");
}
但是,我想同步我的两个进程/线程。我需要一个互斥锁来防止同时访问和一个条件变量来通知读者有数据。
从这里阅读:
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放在结构中。
如何将自定义向量分配器与“包装器”结构集成,以包含互斥锁和条件变量?
答案 0 :(得分:1)
因此我开始创建一个结构:
struct MySharedData { MyVector vec; interprocess_mutex mutex; interprocess_condition cond_empty; }
看起来很清醒。为什么会出现问题?只需添加一个构造函数来初始化向量的分配器。这可能有效:
MySharedData::MySharedData(managed_shared_memory::segment_manager* sm)
: vec(sm)
{}