[Home]Interprocess STL Map

BOOST WIKI | RecentChanges | Preferences | Page List | Links List

Using an shmem/interprocess map that is shared between two processes

For this tutorial to be useful the reader needs an understanding of use of the associative container STL map and familiarity with shmem/interprocess.

For example, define a structure that is the value the map uses, this example has one member.

struct Data {

	boost::posix_time::ptime time;
};

Headers required.

  1. include "boost/shmem/containers/map.hpp"
  2. include <boost/shmem/named_shared_object.hpp>

The definition of the map. The map needs a third template parameter less<long>. The parameter to the less template is the same as the first, key, parameter to the map. It is prudent to typedef the whole definition at this point as it is used extensivley when working with the map.

typedef boost::shmem::map<long,Data,std::less<long>,boost::shmem::allocator<std::pair<long,Data>,

		boost::shmem::named_shared_object::segment_manager> > shmap;

shmap *rp; boost::shmem::named_shared_object segment;

//Create? the memory segment and initialize resources segment.create("SharedMemory?", //segment name

	65536)            //segment size in bytes

The less template with the map key type as its parameter needs to be provided as the first argument to the construct member function of the named_shared_object. shmap is the template parameter to the construct function.

rp=segment.construct<shmap>("SharedMap?")(std::less<long>(),_segment.get_segment_manager());

Data d;

This line would have a lock round it if there was any danger of threading issues.

rp->insert(pair<long,Data>(1,d));

This line isn't run until we've finished using the map in all other processes. The destroy function needs shmap as its template parameter.

logger.segment.destroy<shmap >("SharedMap?");

In an other process that is using the shared memory. The same typedef as above would preceed this. shmap would then be available in the scope of the following code.

phshmap *rp; named_shared_object segment;

//Create? the memory segment and initialize resources if(!segment.open("SharedMemory?"))

	return 0;

The shmap is the template parameter to the find function.

rp =segment.find<shmap >("SharedMap?").first;

The iterator member of the shmap defined above is used to iterate through the map.

//iterate processes for(shmap::iterator i=rp->begin(); i!=rp->end(); i++) {

i->time can be used here

}

To look up a value in the map.

shmap::iterator shmapit=rp->find(1);

shmapit->time could then be used.

segment.close();


BOOST WIKI | RecentChanges | Preferences | Page List | Links List
Edit text of this page | View other revisions
Last edited November 19, 2006 8:40 am (diff)
Search:
Disclaimer: This site not officially maintained by Boost Developers