• 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_named_mutex
12 #include <boost/interprocess/sync/scoped_lock.hpp>
13 #include <boost/interprocess/sync/named_mutex.hpp>
14 #include <fstream>
15 #include <iostream>
16 #include <cstdio>
17 
18 //<-
19 #include "../test/get_process_id_name.hpp"
20 //->
21 
main()22 int main ()
23 {
24    using namespace boost::interprocess;
25    try{
26       struct file_remove
27       {
28       //<-
29       #if 1
30          file_remove() { std::remove(test::get_process_id_name()); }
31          ~file_remove(){ std::remove(test::get_process_id_name()); }
32       #else
33       //->
34          file_remove() { std::remove("file_name"); }
35          ~file_remove(){ std::remove("file_name"); }
36       //<-
37       #endif
38       //->
39       } file_remover;
40       struct mutex_remove
41       {
42       //<-
43       #if 1
44          mutex_remove() { named_mutex::remove(test::get_process_id_name()); }
45          ~mutex_remove(){ named_mutex::remove(test::get_process_id_name()); }
46       #else
47       //->
48          mutex_remove() { named_mutex::remove("fstream_named_mutex"); }
49          ~mutex_remove(){ named_mutex::remove("fstream_named_mutex"); }
50       //<-
51       #endif
52       //->
53       } remover;
54       //<-
55       (void)remover;
56       //->
57 
58       //Open or create the named mutex
59    //<-
60    #if 1
61       named_mutex mutex(open_or_create, test::get_process_id_name());
62    #else
63    //->
64       named_mutex mutex(open_or_create, "fstream_named_mutex");
65    //<-
66    #endif
67    //->
68 
69       //<-
70       #if 1
71       std::ofstream file(test::get_process_id_name());
72       #else
73       //->
74       std::ofstream file("file_name");
75       //<-
76       #endif
77       //->
78 
79       for(int i = 0; i < 10; ++i){
80 
81          //Do some operations...
82 
83          //Write to file atomically
84          scoped_lock<named_mutex> lock(mutex);
85          file << "Process name, ";
86          file << "This is iteration #" << i;
87          file << std::endl;
88       }
89    }
90    catch(interprocess_exception &ex){
91       std::cout << ex.what() << std::endl;
92       return 1;
93    }
94    return 0;
95 }
96 //]
97 #include <boost/interprocess/detail/config_end.hpp>
98