1 //////////////////////////////////////////////////////////////////////////////
3 // (C) Copyright Ion Gaztanaga 2006-2012. 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_aligned_allocation
12 #include <boost/interprocess/managed_shared_memory.hpp>
15 #include "../test/get_process_id_name.hpp"
20 using namespace boost::interprocess;
22 //Remove shared memory on construction and destruction
27 shm_remove() { shared_memory_object::remove(test::get_process_id_name()); }
28 ~shm_remove(){ shared_memory_object::remove(test::get_process_id_name()); }
31 shm_remove() { shared_memory_object::remove("MySharedMemory"); }
32 ~shm_remove(){ shared_memory_object::remove("MySharedMemory"); }
41 //Managed memory segment that allocates portions of a shared memory
42 //segment with the default management algorithm
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 const std::size_t Alignment = 128;
55 //Allocate 100 bytes aligned to Alignment from segment, throwing version
56 void *ptr = managed_shm.allocate_aligned(100, Alignment);
59 assert((static_cast<char*>(ptr)-static_cast<char*>(0)) % Alignment == 0);
62 managed_shm.deallocate(ptr);
64 //Non throwing version
65 ptr = managed_shm.allocate_aligned(100, Alignment, std::nothrow);
68 assert((static_cast<char*>(ptr)-static_cast<char*>(0)) % Alignment == 0);
71 managed_shm.deallocate(ptr);
73 //If we want to efficiently allocate aligned blocks of memory
74 //use managed_shared_memory::PayloadPerAllocation value
75 assert(Alignment > managed_shared_memory::PayloadPerAllocation);
77 //This allocation will maximize the size of the aligned memory
78 //and will increase the possibility of finding more aligned memory
79 ptr = managed_shm.allocate_aligned
80 (3*Alignment - managed_shared_memory::PayloadPerAllocation, Alignment);
83 assert((static_cast<char*>(ptr)-static_cast<char*>(0)) % Alignment == 0);
86 managed_shm.deallocate(ptr);
94 #include <boost/interprocess/managed_windows_shared_memory.hpp>
98 using namespace boost::interprocess;
99 typedef boost::interprocess::
100 managed_windows_shared_memory shared_segment;
102 std::vector<void *> ptrs;
103 shared_segment m_segment(create_only, "shmem", 4096*16);
106 //Now I have several allocate_aligned operations:
107 ptrs.push_back(m_segment.allocate_aligned(128, 128));
111 m_segment.deallocate(ptrs.back());
113 ptrs.push_back(m_segment.allocate_aligned(128, 128));
118 #include <boost/interprocess/detail/config_end.hpp>