]> git.proxmox.com Git - ceph.git/blob - ceph/src/boost/libs/interprocess/example/comp_doc_anonymous_mutexA.cpp
add subtree-ish sources for 12.0.3
[ceph.git] / ceph / src / boost / libs / interprocess / example / comp_doc_anonymous_mutexA.cpp
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_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_anonymous_mutex_shared_data.hpp"
16 #include <iostream>
17 #include <cstdio>
18
19 using namespace boost::interprocess;
20
21 int main ()
22 {
23 try{
24 //Remove shared memory on construction and destruction
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
41 //Set size
42 shm.truncate(sizeof(shared_memory_log));
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 shared_memory_log * data = new (addr) shared_memory_log;
55
56 //Write some logs
57 for(int i = 0; i < shared_memory_log::NumItems; ++i){
58 //Lock the mutex
59 scoped_lock<interprocess_mutex> lock(data->mutex);
60 std::sprintf(data->items[(data->current_line++) % shared_memory_log::NumItems]
61 ,"%s_%d", "process_a", i);
62 if(i == (shared_memory_log::NumItems-1))
63 data->end_a = true;
64 //Mutex is released here
65 }
66
67 //Wait until the other process ends
68 while(1){
69 scoped_lock<interprocess_mutex> lock(data->mutex);
70 if(data->end_b)
71 break;
72 }
73 }
74 catch(interprocess_exception &ex){
75 std::cout << ex.what() << std::endl;
76 return 1;
77 }
78 return 0;
79 }
80 //]
81 #include <boost/interprocess/detail/config_end.hpp>