1 ////////////////////////////////////////////////////////////////////////////// 2 // 3 // (C) Copyright Ion Gaztanaga 2006-2012. Distributed under the Boost 4 // Software License, Version 1.0. (See accompanying file 5 // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) 6 // 7 // See http://www.boost.org/libs/interprocess for documentation. 8 // 9 ////////////////////////////////////////////////////////////////////////////// 10 #include <boost/interprocess/detail/config_begin.hpp> 11 //[doc_anonymous_upgradable_mutexA 12 #include <boost/interprocess/shared_memory_object.hpp> 13 #include <boost/interprocess/mapped_region.hpp> 14 #include <boost/interprocess/sync/scoped_lock.hpp> 15 #include "doc_upgradable_mutex_shared_data.hpp" 16 #include <iostream> 17 #include <cstdio> 18 19 using namespace boost::interprocess; 20 main()21int main () 22 { 23 //Remove shared memory on destruction 24 struct shm_remove 25 { 26 ~shm_remove(){ shared_memory_object::remove("MySharedMemory"); } 27 } remover; 28 //<- 29 (void)remover; 30 //-> 31 32 //Create a shared memory object. 33 shared_memory_object shm 34 (create_only //only create 35 ,"MySharedMemory" //name 36 ,read_write //read-write mode 37 ); 38 39 //Set size 40 shm.truncate(sizeof(shared_data)); 41 42 //Map the whole shared memory in this process 43 mapped_region region 44 (shm //What to map 45 ,read_write //Map it as read-write 46 ); 47 48 //Get the address of the mapped region 49 void * addr = region.get_address(); 50 51 //Construct the shared structure in memory 52 shared_data * data = new (addr) shared_data; 53 54 //Write some logs 55 for(int i = 0; i < shared_data::NumItems; ++i){ 56 //Lock the upgradable_mutex 57 scoped_lock<interprocess_upgradable_mutex> lock(data->upgradable_mutex); 58 std::sprintf(data->items[(data->current_line++) % shared_data::NumItems] 59 ,"%s_%d", "process_a", i); 60 if(i == (shared_data::NumItems-1)) 61 data->end_a = true; 62 //Mutex is released here 63 } 64 65 //Wait until the other process ends 66 while(1){ 67 scoped_lock<interprocess_upgradable_mutex> lock(data->upgradable_mutex); 68 if(data->end_b) 69 break; 70 } 71 72 return 0; 73 } 74 //] 75 #include <boost/interprocess/detail/config_end.hpp> 76