• 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 //[doc_anonymous_conditionA
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 <iostream>
16 #include <cstdio>
17 #include "doc_anonymous_condition_shared_data.hpp"
18 
19 using namespace boost::interprocess;
20 
main()21 int main ()
22 {
23 
24    //Erase previous shared memory and schedule erasure on exit
25    struct shm_remove
26    {
27       shm_remove() { shared_memory_object::remove("MySharedMemory"); }
28       ~shm_remove(){ shared_memory_object::remove("MySharedMemory"); }
29    } remover;
30    //<-
31    (void)remover;
32    //->
33 
34    //Create a shared memory object.
35    shared_memory_object shm
36       (create_only               //only create
37       ,"MySharedMemory"           //name
38       ,read_write                //read-write mode
39       );
40    try{
41       //Set size
42       shm.truncate(sizeof(trace_queue));
43 
44       //Map the whole shared memory in this process
45       mapped_region region
46          (shm                       //What to map
47          ,read_write //Map it as read-write
48          );
49 
50       //Get the address of the mapped region
51       void * addr       = region.get_address();
52 
53       //Construct the shared structure in memory
54       trace_queue * data = new (addr) trace_queue;
55 
56       const int NumMsg = 100;
57 
58       for(int i = 0; i < NumMsg; ++i){
59          scoped_lock<interprocess_mutex> lock(data->mutex);
60          if(data->message_in){
61             data->cond_full.wait(lock);
62          }
63          if(i == (NumMsg-1))
64             std::sprintf(data->items, "%s", "last message");
65          else
66             std::sprintf(data->items, "%s_%d", "my_trace", i);
67 
68          //Notify to the other process that there is a message
69          data->cond_empty.notify_one();
70 
71          //Mark message buffer as full
72          data->message_in = true;
73       }
74    }
75    catch(interprocess_exception &ex){
76       std::cout << ex.what() << std::endl;
77       return 1;
78    }
79 
80    return 0;
81 }
82 //]
83