/^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Boost Shared Memory
// This vector is stored in a shared memory
// Date : 26 - July -2009
// Author: Prakhar Dubey (prakharprakhar@gmail.com)
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#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 segment */
typedef 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 segment */
typedef vector<int, ShmemAllocator> MyVector;
/* Main function. For parent process argc == 1, for child process argc == 2 */
int main(int argc, char *argv[])
{
shared_memory_object::remove("MySharedMemory");
//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);
return 0;
}
No comments:
Post a Comment