如何获取boost进程内共享内存

时间:2017-12-06 15:13:37

标签: c++ boost shared-memory boost-interprocess

根据Boost docs

指南

可以创建某种类型的命名向量(例如double)

  using namespace boost::interprocess;
  typedef allocator<int, managed_shared_memory::segment_manager>  ShmemAllocator;
  managed_shared_memory segment(create_only, "MySharedMemory", 65536);

  //Initialize shared memory STL-compatible allocator
  const ShmemAllocator alloc_inst (segment.get_segment_manager());

  //Construct a vector named "values_A" in shared memory with argument alloc_inst
  MyVector *vA= segment.construct<MyVector>("values_A")(alloc_inst);
  MyVector *vB= segment.construct<MyVector>("values_B")(alloc_inst);

  for(int i = 0; i < 100; ++i)  //Insert data in the vector
     vA->push_back(i);

然后,如果客户端进程知道共享对象的名称(&#34; values_A &#34;和&#34; values_B &#34;)它很容易访问它们。

  managed_shared_memory segment(open_only, "MySharedMemory");
  MyVector *vA_client = segment.find<MyVector>("values_A").first;
  MyVector *vB_client = segment.find<MyVector>("values_B").first;

  //Use vector in reverse order
  std::sort(vA_client->rbegin(), vA_client->rend());

但是,如果客户不知道这些对象的名称?

如何获取这些对象的列表? {&#34; values_A &#34; ,&#34; values_B &#34;}。

如果有其他类型的对象(&#34; MyVector2 &#34;)已注册(名为&#34; intA &#34;,& #34; intB &#34;) - 您如何仅过滤那些类型为 MyVector 的人?

我怀疑它与方法 named_begin named_end 有关,但我不知道如何使用它。

感谢您的帮助:)

1 个答案:

答案 0 :(得分:2)

这些方法是段管理器界面的一部分。

  

直接使用时请注意竞争条件。在多进程情况下,find_or_construct会在findconstruct之外执行其他操作。

示例:

<强> Live On Coliru

#include <boost/interprocess/managed_mapped_file.hpp>
#include <boost/interprocess/containers/vector.hpp>
#include <iostream>
namespace bip = boost::interprocess;

using Shared = bip::managed_mapped_file;
using Manager = Shared::segment_manager;
template <typename T> using Alloc = bip::allocator<T, Manager>;
template <typename T> using V = boost::container::vector<T, Alloc<T> >;

int main() {
    bip::managed_mapped_file mmf(bip::open_or_create, "test.bin", 10ull<<10);
    auto* segment = mmf.get_segment_manager();

    for (auto it = segment->named_begin(); it != segment->named_end(); ++it) {
        std::cout << "before: " << std::string(it->name(), it->name_length()) << "\n";
    }

    for (auto next : { "foo", "bar", "qux" }) {
        if (!mmf.find<V<int> >(next).first)
        {
            mmf.find_or_construct<V<int> >(next)(segment);
            break;
        }
    }

    for (auto it = segment->named_begin(); it != segment->named_end(); ++it) {
        std::cout << "after:  " << std::string(it->name(), it->name_length()) << "\n";
    }
}

打印(首次运行):

after:  foo

第二轮:

before: foo
after:  bar
after:  foo

第三次运行:

before: bar
before: foo
after:  bar
after:  foo
after:  qux

第四次(及以后)运行:

before: bar
before: foo
before: qux
after:  bar
after:  foo
after:  qux