1 //////////////////////////////////////////////////////////////////////////////
3 // (C) Copyright Ion Gaztanaga 2006-2009. Distributed under the Boost
4 // Software License, Version 1.0. (See accompanying file
5 // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
7 // See http://www.boost.org/libs/interprocess for documentation.
9 //////////////////////////////////////////////////////////////////////////////
10 #include <boost/interprocess/detail/config_begin.hpp>
11 //[doc_managed_multiple_allocation
12 #include <boost/interprocess/managed_shared_memory.hpp>
13 #include <boost/interprocess/detail/move.hpp> //boost::interprocess::move
14 #include <cassert>//assert
15 #include <cstring>//std::memset
16 #include <new> //std::nothrow
17 #include <vector> //std::vector
19 #include "../test/get_process_id_name.hpp"
24 using namespace boost::interprocess;
25 typedef managed_shared_memory::multiallocation_chain multiallocation_chain;
27 //Remove shared memory on construction and destruction
32 shm_remove() { shared_memory_object::remove(test::get_process_id_name()); }
33 ~shm_remove(){ shared_memory_object::remove(test::get_process_id_name()); }
36 shm_remove() { shared_memory_object::remove("MySharedMemory"); }
37 ~shm_remove(){ shared_memory_object::remove("MySharedMemory"); }
45 managed_shared_memory managed_shm(create_only,test::get_process_id_name(), 65536);
48 managed_shared_memory managed_shm(create_only,"MySharedMemory", 65536);
53 //Allocate 16 elements of 100 bytes in a single call. Non-throwing version.
54 multiallocation_chain chain(managed_shm.allocate_many(100, 16, std::nothrow));
56 //Check if the memory allocation was successful
57 if(chain.empty()) return 1;
60 std::vector<void*> allocated_buffers;
63 while(!chain.empty()){
64 void *buf = chain.front();
66 allocated_buffers.push_back(buf);
67 //The iterator must be incremented before overwriting memory
68 //because otherwise, the iterator is invalidated.
69 std::memset(buf, 0, 100);
73 while(!allocated_buffers.empty()){
74 managed_shm.deallocate(allocated_buffers.back());
75 allocated_buffers.pop_back();
78 //Allocate 10 buffers of different sizes in a single call. Throwing version
79 std::size_t sizes[10];
80 for(std::size_t i = 0; i < 10; ++i)
83 chain = managed_shm.allocate_many(sizes, 10);
84 managed_shm.deallocate_many(boost::interprocess::move(chain));
88 #include <boost/interprocess/detail/config_end.hpp>