comp_doc_anonymous_upgradable_mutexB.cpp 2.2 KB

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