/* Boost.MultiIndex example of use of Boost.Interprocess allocators. * * Copyright 2003-2008 Joaquin M Lopez Munoz. * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) * * See http://www.boost.org/libs/multi_index for library home page. */ #if !defined(NDEBUG) #define BOOST_MULTI_INDEX_ENABLE_INVARIANT_CHECKING #define BOOST_MULTI_INDEX_ENABLE_SAFE_MODE #endif #include /* keep it first to prevent nasty warns in MSVC */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include using boost::multi_index_container; using namespace boost::multi_index; namespace bip=boost::interprocess; /* shared_string is a string type placeable in shared memory, * courtesy of Boost.Interprocess. */ typedef bip::basic_string< char,std::char_traits, bip::allocator > shared_string; /* Book record. All its members can be placed in shared memory, * hence the structure itself can too. */ struct book { shared_string name; shared_string author; unsigned pages; unsigned prize; unsigned prize2; book(const shared_string::allocator_type& al): name(al),author(al),pages(0),prize(0),prize2(0) {} friend std::ostream& operator<<(std::ostream& os,const book& b) { os<, ordered_non_unique< BOOST_MULTI_INDEX_MEMBER(book,shared_string,name), partial_str_less >, hashed_unique< BOOST_MULTI_INDEX_MEMBER(book,unsigned,prize) >, hashed_unique< BOOST_MULTI_INDEX_MEMBER(book,unsigned,prize2) > >, bip::allocator > book_container; /* A small utility to get data entered via std::cin */ template void enter(const char* msg,T& t) { std::cout<>t; } void enter(const char* msg,std::string& str) { std::cout<("book container")( book_container::ctor_args_list(), book_container::allocator_type(seg.get_segment_manager())); std::string command_info= "1. list books by author\n" "2. list all books by prize\n" "3. insert a book\n" "4. delete a book\n" "0. exit\n"; std::cout< lock(mutex); std::pair rng; if(author.empty()){ rng=std::make_pair(pbc->begin(),pbc->end()); } else{ rng=pbc->equal_range( shared_string( author.c_str(), shared_string::allocator_type(seg.get_segment_manager()))); } if(rng.first==rng.second){ std::cout<<"no entries\n"; } else{ std::copy( rng.first,rng.second,std::ostream_iterator(std::cout)); } break; } case 2:{ /* list all books by prize */ bip::scoped_lock lock(mutex); std::copy( get<2>(*pbc).begin(),get<2>(*pbc).end(), std::ostream_iterator(std::cout)); break; } case 3:{ /* insert a book */ book b(shared_string::allocator_type(seg.get_segment_manager())); enter("author: ",b.author); enter("name: " ,b.name); enter("prize: " ,b.prize); enter("pages: " ,b.pages); std::cout<<"insert the following?\n"< lock(mutex); pbc->insert(b); } break; } default:{ std::cout<<"select one option:\n"<