• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
12 //[doc_anonymous_upgradable_mutexB
13 #include <boost/interprocess/shared_memory_object.hpp>
14 #include <boost/interprocess/mapped_region.hpp>
15 #include <boost/interprocess/sync/scoped_lock.hpp>
16 #include "doc_upgradable_mutex_shared_data.hpp"
17 #include <iostream>
18 #include <cstdio>
19 
20 using namespace boost::interprocess;
21 
main()22 int main ()
23 {
24    //Remove shared memory on destruction
25    struct shm_remove
26    {
27       ~shm_remove(){ shared_memory_object::remove("MySharedMemory"); }
28    } remover;
29    //<-
30    (void)remover;
31    //->
32 
33    //Open the shared memory object.
34    shared_memory_object shm
35       (open_only                    //only create
36       ,"MySharedMemory"              //name
37       ,read_write  //read-write mode
38       );
39 
40    //Map the whole shared memory in this process
41    mapped_region region
42       (shm                       //What to map
43       ,read_write //Map it as read-write
44       );
45 
46    //Get the address of the mapped region
47    void * addr       = region.get_address();
48 
49    //Construct the shared structure in memory
50    shared_data * data = static_cast<shared_data*>(addr);
51 
52    //Write some logs
53    for(int i = 0; i < 100; ++i){
54       //Lock the upgradable_mutex
55       scoped_lock<interprocess_upgradable_mutex> lock(data->upgradable_mutex);
56       std::sprintf(data->items[(data->current_line++) % shared_data::NumItems]
57                ,"%s_%d", "process_a", i);
58       if(i == (shared_data::NumItems-1))
59          data->end_b = true;
60       //Mutex is released here
61    }
62 
63    //Wait until the other process ends
64    while(1){
65       scoped_lock<interprocess_upgradable_mutex> lock(data->upgradable_mutex);
66       if(data->end_a)
67          break;
68    }
69    return 0;
70 }
71 //]
72 
73 #include <boost/interprocess/detail/config_end.hpp>
74