2. Quick Guide (for friends eager to learn about boost. interprocess)
Use shared memory as an anonymous memory block pool
Create a named Shared Memory Object Use an offset smart pointer for shared memory Create a container (vector) in the shared memory) Create a map in the shared memory) |
Use shared memory as an anonymous memory block pool
You can only allocate part of the shared memory segment, copy the message to that buffer, and then send the offset of that part of the shared memory to another process. Example:
#include <boost/interprocess/managed_shared_memory.hpp>#include <cstdlib> //std::system#include <sstream> int main (int argc, char *argv[]){ using namespace boost::interprocess; if(argc == 1){ //Parent process //Remove shared memory on construction anddestruction struct shm_remove { shm_remove() { shared_memory_object::remove("MySharedMemory");} ~shm_remove(){ shared_memory_object::remove("MySharedMemory"); } }remover; //Create a managed shared memory segment managed_shared_memory segment(create_only,"MySharedMemory",65536); //Allocate a portion of the segment (rawmemory) managed_shared_memory::size_type free_memory = segment.get_free_memory(); void * shptr = segment.allocate(1024/*bytes toallocate*/); //Check invariant if(free_memory <= segment.get_free_memory()) return 1; //An handle from the base address canidentify any byte of the shared //memory segment even if it is mapped indifferent base addresses managed_shared_memory::handle_t handle = segment.get_handle_from_address(shptr); std::stringstream s; s<< argv[0]<< " "<< handle; s<< std::ends; //Launch child process if(0 != std::system(s.str().c_str())) return 1; //Check memory has been freed if(free_memory != segment.get_free_memory()) return 1; } else{ //Open managed segment managed_shared_memory segment(open_only,"MySharedMemory"); //An handle from the base address canidentify any byte of the shared //memory segment even if it is mapped indifferent base addresses managed_shared_memory::handle_t handle = 0; //Obtain handle value std::stringstream s; s<< argv[1];s >> handle; //Get buffer local address from handle void *msg = segment.get_address_from_handle(handle); //Deallocate previously allocated memory segment.deallocate(msg); } return 0;}
Create a named Shared Memory Object
You can create objects in the shared memory segment and give them string-type names so that other processes can find them and use them, and delete them from the memory segment when the objects are no longer in use. Example:
#include <boost/interprocess/managed_shared_memory.hpp>#include <cstdlib> //std::system#include <cstddef>#include <cassert>#include <utility> int main(int argc, char *argv[]){ using namespace boost::interprocess; typedef std::pair<double, int> MyType; if(argc == 1){ //Parent process //Remove shared memory on construction and destruction struct shm_remove { shm_remove() { shared_memory_object::remove("MySharedMemory"); } ~shm_remove(){ shared_memory_object::remove("MySharedMemory"); } } remover; //Construct managed shared memory managed_shared_memory segment(create_only, "MySharedMemory", 65536); //Create an object of MyType initialized to {0.0, 0} MyType *instance = segment.construct<MyType> ("MyType instance") //name of the object (0.0, 0); //ctor first argument //Create an array of 10 elements of MyType initialized to {0.0, 0} MyType *array = segment.construct<MyType> ("MyType array") //name of the object [10] //number of elements (0.0, 0); //Same two ctor arguments for all objects //Create an array of 3 elements of MyType initializing each one //to a different value {0.0, 0}, {1.0, 1}, {2.0, 2}... float float_initializer[3] = { 0.0, 1.0, 2.0 }; int int_initializer[3] = { 0, 1, 2 }; MyType *array_it = segment.construct_it<MyType> ("MyType array from it") //name of the object [3] //number of elements ( &float_initializer[0] //Iterator for the 1st ctor argument , &int_initializer[0]); //Iterator for the 2nd ctor argument //Launch child process std::string s(argv[0]); s += " child "; if(0 != std::system(s.c_str())) return 1; //Check child has destroyed all objects if(segment.find<MyType>("MyType array").first || segment.find<MyType>("MyType instance").first || segment.find<MyType>("MyType array from it").first) return 1; } else{ //Open managed shared memory managed_shared_memory segment(open_only, "MySharedMemory"); std::pair<MyType*, managed_shared_memory::size_type> res; //Find the array res = segment.find<MyType> ("MyType array"); //Length should be 10 if(res.second != 10) return 1; //Find the object res = segment.find<MyType> ("MyType instance"); //Length should be 1 if(res.second != 1) return 1; //Find the array constructed from iterators res = segment.find<MyType> ("MyType array from it"); //Length should be 3 if(res.second != 3) return 1; //We're done, delete all the objects segment.destroy<MyType>("MyType array"); segment.destroy<MyType>("MyType instance"); segment.destroy<MyType>("MyType array from it"); } return 0;}
Use an offset smart pointer for shared memory
Boost. interprocess provides the offset_ptr smart pointer family as an offset pointer to store the distance between the offset pointer address and the object address. When offset_ptr is placed in the shared memory segment, it can safely point to the objects in this shared memory segment, and even work normally when the memory segment is mapped to different base addresses by different processes.
This allows objects with pointer members to be placed in the shared memory. For example, if we want to create a linked list in the shared memory:
#include <boost/interprocess/managed_shared_memory.hpp>#include <boost/interprocess/offset_ptr.hpp> using namespace boost::interprocess; //Shared memory linked list nodestruct list_node{ offset_ptr<list_node> next; int value;}; int main (){ //Remove shared memory on construction and destruction struct shm_remove { shm_remove() { shared_memory_object::remove("MySharedMemory"); } ~shm_remove(){ shared_memory_object::remove("MySharedMemory"); } } remover; //Create shared memory managed_shared_memory segment(create_only, "MySharedMemory", //segment name 65536); //Create linked list with 10 nodes in shared memory offset_ptr<list_node> prev = 0, current, first; int i; for(i = 0; i < 10; ++i, prev = current){ current = static_cast<list_node*>(segment.allocate(sizeof(list_node))); current->value = i; current->next = 0; if(!prev) first = current; else prev->next = current; } //Communicate list to other processes //. . . //When done, destroy list for(current = first; current; /**/){ prev = current; current = current->next; segment.deallocate(prev.get()); } return 0;}
To better process the basic data structure, boost. interprocess provides containers similar to vector, list, and map, so you can avoid these data structure manuals, just like using standard containers.
Create a container (vector) in the shared memory)
Boost. interprocess allows you to create complex objects in the shared memory and memory ing files. For example, we can create a class STL container in the shared memory. To achieve this, we only need to create a special (controlled) shared memory segment, declare a boost. interprocess distributor, and then create a vector in the shared memory like other objects.
The class that allows you to create complex structures in the shared memory is boost: interprocess: managed_shared_memory, which is easy to use. Run the following example without parameters:
#include <boost/interprocess/managed_shared_memory.hpp>#include <boost/interprocess/containers/vector.hpp>#include <boost/interprocess/allocators/allocator.hpp>#include <string>#include <cstdlib> //std::system using namespace boost::interprocess; //Define an STL compatible allocator of ints that allocates from the managed_shared_memory.//This allocator will allow placing containers in the segmenttypedef allocator<int, managed_shared_memory::segment_manager> ShmemAllocator; //Alias a vector that uses the previous STL-like allocator so that allocates//its values from the segmenttypedef vector<int, ShmemAllocator> MyVector; //Main function. For parent process argc == 1, for child process argc == 2int main(int argc, char *argv[]){ if(argc == 1){ //Parent process //Remove shared memory on construction and destruction struct shm_remove { shm_remove() { shared_memory_object::remove("MySharedMemory"); } ~shm_remove(){ shared_memory_object::remove("MySharedMemory"); } } remover; //Create a new segment with given name and size 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 "MyVector" in shared memory with argument alloc_inst MyVector *myvector = segment.construct<MyVector>("MyVector")(alloc_inst); for(int i = 0; i < 100; ++i) //Insert data in the vector myvector->push_back(i); //Launch child process std::string s(argv[0]); s += " child "; if(0 != std::system(s.c_str())) return 1; //Check child has destroyed the vector if(segment.find<MyVector>("MyVector").first) return 1; } else{ //Child process //Open the managed segment managed_shared_memory segment(open_only, "MySharedMemory"); //Find the vector using the c-string name MyVector *myvector = segment.find<MyVector>("MyVector").first; //Use vector in reverse order std::sort(myvector->rbegin(), myvector->rend()); //When done, destroy the vector from the segment segment.destroy<MyVector>("MyVector"); } return 0;};
The parent process creates a special shared memory class that allows the construction of many named complex data structures. Sub-processes (written as parent process by mistake in the original article) execute the same program with parameters, open the shared memory, use the vector, and delete it.
Create a map in the shared memory)
Like vector, boost. interprocess allows you to create a ing table in the shared memory and memory ing files. The only difference is that, like the standard associated container, when the distributor is passed into the constructor, the map of boost. interprocess also needs to define a comparison function:
#include <boost/interprocess/managed_shared_memory.hpp>#include <boost/interprocess/containers/map.hpp>#include <boost/interprocess/allocators/allocator.hpp>#include <functional>#include <utility> int main (){ using namespace boost::interprocess; //Remove shared memory on construction and destruction struct shm_remove { shm_remove() { shared_memory_object::remove("MySharedMemory"); } ~shm_remove(){ shared_memory_object::remove("MySharedMemory"); } } remover; //Shared memory front-end that is able to construct objects //associated with a c-string. Erase previous shared memory with the name //to be used and create the memory segment at the specified address and initialize resources managed_shared_memory segment (create_only ,"MySharedMemory" //segment name ,65536); //segment size in bytes //Note that map<Key, MappedType>'s value_type is std::pair<const Key, MappedType>, //so the allocator must allocate that pair. typedef int KeyType; typedef float MappedType; typedef std::pair<const int, float> ValueType; //Alias an STL compatible allocator of for the map. //This allocator will allow to place containers //in managed shared memory segments typedef allocator<ValueType, managed_shared_memory::segment_manager> ShmemAllocator; //Alias a map of ints that uses the previous STL-like allocator. //Note that the third parameter argument is the ordering function //of the map, just like with std::map, used to compare the keys. typedef map<KeyType, MappedType, std::less<KeyType>, ShmemAllocator> MyMap; //Initialize the shared memory STL-compatible allocator ShmemAllocator alloc_inst (segment.get_segment_manager()); //Construct a shared memory map. //Note that the first parameter is the comparison function, //and the second one the allocator. //This the same signature as std::map's constructor taking an allocator MyMap *mymap = segment.construct<MyMap>("MyMap") //object name (std::less<int>() //first ctor parameter ,alloc_inst); //second ctor parameter //Insert data in the map for(int i = 0; i < 100; ++i){ mymap->insert(std::pair<const int, float>(i, (float)i)); } return 0;}
For more examples (including container containers), refer to the "Container" section"