1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
|
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/interprocess/containers/string.hpp>
#include <iostream>
#include <boost/unordered_map.hpp> //boost::unordered_map
#include <functional> //std::equal_to
#include <boost/functional/hash.hpp> //boost::hash
using namespace boost::interprocess;
//Typedefs of allocators and containers
typedef managed_shared_memory::segment_manager segment_manager_t;
typedef allocator<void, segment_manager_t> void_allocator;
typedef allocator<char, segment_manager_t> char_allocator;
typedef basic_string<char, std::char_traits<char>, char_allocator> char_string;
typedef int complex_data;
//Definition of the map holding a string as key and complex_data as mapped type
typedef std::pair<const char_string, complex_data> map_value_type;
typedef std::pair<char_string, complex_data> movable_to_map_value_type;
typedef allocator<map_value_type, segment_manager_t> map_value_type_allocator;
typedef boost::unordered_multimap < char_string, complex_data
, boost::hash<char_string > ,std::equal_to<char_string >
, map_value_type_allocator> complex_map_type2;
complex_map_type2 * mymap;
int f(void_allocator alloc_inst) {
for(int i = 0; i < 1000; ++i){
//Both key(string) and value(complex_data) need an allocator in their constructors
char_string key_object("test", alloc_inst);
map_value_type value(key_object, i);
//Modify values and insert them in the map
mymap->insert(value);
}
}
int main ()
{
shared_memory_object::remove("MySharedMemory");
remove_shared_memory_on_destroy remove_on_destroy("MySharedMemory");
{
//Create shared memory
managed_shared_memory segment(create_only,"MySharedMemory", 65530);
//An allocator convertible to any allocator<T, segment_manager_t> type
void_allocator alloc_inst (segment.get_segment_manager());
complex_map_type2 *mymap = segment.construct<complex_map_type2>("MyHashMap") //object name
( 3, boost::hash<char_string>(), std::equal_to<char_string>() //
, segment.get_allocator<map_value_type>()); //allocator instance
std::cout << 1 << std::endl;
f(alloc_inst);
std::cout << 1 << std::endl;
for(complex_map_type2::iterator i = mymap->begin(); i != mymap->end(); ++i){
std::cout << i->first << "=" << i->second << std::endl;
}
}
return 0;
}
|