gpt4 book ai didi

c++ - 将进程间包装器 boost 到分配器

转载 作者:行者123 更新时间:2023-11-30 05:00:47 25 4
gpt4 key购买 nike

我在共享内存中有多个索引容器

//Create hash
typedef boost::multi_index::multi_index_container<
My_Key,
My_Key_hash_indices,
bip::allocator<MyKey, bip::managed_shared_memory::segment_manager>
> MyGlobalHash;

我需要根据配置使用以下之一:

  1. bip::managed_mapped_file
  2. bip::managed_shared_memory

有没有办法在不创建这两种类型的情况下做到这一点,比如为分配器创建一个包装类并为这两种类型继承。

更多代码在 http://coliru.stacked-crooked.com/a/09ea79752512fad8

最佳答案

不,你不需要那个。一个快速的静态断言得知默认的段管理器类型是相同的:

static_assert(std::is_same<
bip::managed_shared_memory::segment_manager,
bip::managed_mapped_file::segment_manager>{}, "incompatible segments");

所以,你可以只使用一个:

using SegmentManager = bip::managed_shared_memory::segment_manager;

演示

Live On Coliru

#include <iostream>
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/managed_mapped_file.hpp>
#include <boost/interprocess/allocators/allocator.hpp>

namespace bip = boost::interprocess;

static_assert(std::is_same<
bip::managed_shared_memory::segment_manager,
bip::managed_mapped_file::segment_manager>{}, "incompatible segments");
using SegmentManager = bip::managed_shared_memory::segment_manager;

struct X {
int i = 0;
};

#include <boost/multi_index_container.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/ordered_index.hpp>

namespace bmi = boost::multi_index;

using Table = bmi::multi_index_container<X,
bmi::indexed_by< bmi::ordered_unique< bmi::tag<struct byI>, bmi::member<X, int, &X::i> > >,
bip::allocator<X, SegmentManager>
>;

void dump(Table const& t) {
std::cout << "table: ";
for(auto& x : t)
std::cout << x.i << "; ";
std::cout << std::endl;
}

void run_test(Table& table) {
dump(table);

if (table.empty()) {
table.insert({{1}, {2}, {3}, {4}});
} else {
table.insert({5});
}

dump(table);

table.erase(table.begin());
dump(table);
}

int main() {
{
bip::managed_shared_memory segment(bip::open_or_create, "msm", 10ul<<20);
run_test(*segment.template find_or_construct<Table>("name")(segment.get_segment_manager()));
}
{
bip::managed_mapped_file segment(bip::open_or_create, "mmf", 10ul<<20);
run_test(*segment.template find_or_construct<Table>("name")(segment.get_segment_manager()));
}
}

打印(在我的系统上)例如:

table: 2; 3; 4; 
table: 2; 3; 4; 5;
table: 3; 4; 5;
table: 2; 3; 4;
table: 2; 3; 4; 5;
table: 3; 4; 5;

关于c++ - 将进程间包装器 boost 到分配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50586904/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com