【发布时间】:2018-05-16 11:16:00
【问题描述】:
我正在使用共享向量跨内存共享对象:
using ShmemAllocator = bip::allocator<T, bip::managed_shared_memory::segment_manager>;
using MyVector = bip::vector<T, ShmemAllocator>;
bip::permissions perm;
perm.set_unrestricted();
segment.reset(new bip::managed_shared_memory(bip::open_or_create, shared_memory_name, numBytes, 0, perm));
const ShmemAllocator alloc_inst(segment->get_segment_manager());
vec = segment->find_or_construct<MyVector>(shared_vector_name)(alloc_inst);
请注意,向量是在 managed_shared_memory 对象中创建的,它是通过指定字节数而不是向量元素数来创建的。
然后我将元素写入向量:
int write(const std::vector<T>& vec)
{
bip::scoped_lock<bip::named_mutex> lock(*sdc.mutex);
for(const auto& item : vec)
{
sdc.vec->push_back(item);
}
sdc.cond_empty->notify_all();
}
在写入之前检查我是否有足够的空间来写入所有元素的最安全方法是什么?我真的很想避免简单地分配大量字节并希望我永远不会命中它!
【问题讨论】:
-
致电
vector::reserve? -
@VTT 可能会失败。检查capacity() 已经接近了
-
@sehe 我没有看到您的评论并实施了 VTT 可能建议的内容,因此我尝试做一个 reserve(vec.size() + newVec.size()) 如果失败,我捕获并返回错误。 capacity() 是实现我最终所做的正确方法吗?
-
capacity()是回答粗体问题的正确方法“在写作之前检查我是否有足够的空间来写所有元素的最安全方法是什么?”。但是背景故事表明您想知道“我如何确保我的内存段足够大以包含我的数据(例如向量)?” 这就是我回答了我的问题。
标签: c++ c++11 boost shared-memory boost-interprocess