Advertisement
TShiva

boost_shared_memory

Aug 11th, 2017
246
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.35 KB | None | 0 0
  1. #include <boost/interprocess/managed_shared_memory.hpp>
  2. #include <boost/interprocess/containers/vector.hpp>
  3. #include <boost/interprocess/allocators/allocator.hpp>
  4. #include <string>
  5. #include <cstdlib> //std::system
  6.  
  7. using namespace boost::interprocess;
  8.  
  9. //Define an STL compatible allocator of ints that allocates from the managed_shared_memory.
  10. //This allocator will allow placing containers in the segment
  11. typedef allocator<int, managed_shared_memory::segment_manager>  ShmemAllocator;
  12.  
  13. //Alias a vector that uses the previous STL-like allocator so that allocates
  14. //its values from the segment
  15. typedef vector<int, ShmemAllocator> MyVector;
  16.  
  17. //Main function. For parent process argc == 1, for child process argc == 2
  18. int main(int argc, char *argv[])
  19. {
  20.     if(argc == 1){ //Parent process
  21.         //Remove shared memory on construction and destruction
  22.         struct shm_remove
  23.         {
  24.             shm_remove() { shared_memory_object::remove("MySharedMemory"); }
  25.             ~shm_remove(){ shared_memory_object::remove("MySharedMemory"); }
  26.         } remover;
  27.  
  28.         //Create a new segment with given name and size
  29.         managed_shared_memory segment(create_only, "MySharedMemory", 65536);
  30.  
  31.         //Initialize shared memory STL-compatible allocator
  32.         const ShmemAllocator alloc_inst (segment.get_segment_manager());
  33.  
  34.         //Construct a vector named "MyVector" in shared memory with argument alloc_inst
  35.         MyVector *myvector = segment.construct<MyVector>("MyVector")(alloc_inst);
  36.  
  37.         for(int i = 0; i < 100; ++i)  //Insert data in the vector
  38.             myvector->push_back(i);
  39.  
  40.         //Launch child process
  41.         std::string s(argv[0]); s += " child ";
  42.         if(0 != std::system(s.c_str()))
  43.             return 1;
  44.  
  45.         //Check child has destroyed the vector
  46.         if(segment.find<MyVector>("MyVector").first)
  47.             return 1;
  48.     }
  49.     else{ //Child process
  50.         //Open the managed segment
  51.         managed_shared_memory segment(open_only, "MySharedMemory");
  52.  
  53.         //Find the vector using the c-string name
  54.         MyVector *myvector = segment.find<MyVector>("MyVector").first;
  55.  
  56.         //Use vector in reverse order
  57.         std::sort(myvector->rbegin(), myvector->rend());
  58.  
  59.         //When done, destroy the vector from the segment
  60.         segment.destroy<MyVector>("MyVector");
  61.     }
  62.  
  63.     return 0;
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement