doc_named_mutex.cpp 2.4 KB

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