comp_doc_anonymous_mutexA.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. using namespace boost::interprocess;
  19. int main ()
  20. {
  21. try{
  22. //Remove shared memory on construction and destruction
  23. struct shm_remove
  24. {
  25. shm_remove() { shared_memory_object::remove("MySharedMemory"); }
  26. ~shm_remove(){ shared_memory_object::remove("MySharedMemory"); }
  27. } remover;
  28. //<-
  29. (void)remover;
  30. //->
  31. //Create a shared memory object.
  32. shared_memory_object shm
  33. (create_only //only create
  34. ,"MySharedMemory" //name
  35. ,read_write //read-write mode
  36. );
  37. //Set size
  38. shm.truncate(sizeof(shared_memory_log));
  39. //Map the whole shared memory in this process
  40. mapped_region region
  41. (shm //What to map
  42. ,read_write //Map it as read-write
  43. );
  44. //Get the address of the mapped region
  45. void * addr = region.get_address();
  46. //Construct the shared structure in memory
  47. shared_memory_log * data = new (addr) shared_memory_log;
  48. //Write some logs
  49. for(int i = 0; i < shared_memory_log::NumItems; ++i){
  50. //Lock the mutex
  51. scoped_lock<interprocess_mutex> lock(data->mutex);
  52. std::sprintf(data->items[(data->current_line++) % shared_memory_log::NumItems]
  53. ,"%s_%d", "process_a", i);
  54. if(i == (shared_memory_log::NumItems-1))
  55. data->end_a = true;
  56. //Mutex is released here
  57. }
  58. //Wait until the other process ends
  59. while(1){
  60. scoped_lock<interprocess_mutex> lock(data->mutex);
  61. if(data->end_b)
  62. break;
  63. }
  64. }
  65. catch(interprocess_exception &ex){
  66. std::cout << ex.what() << std::endl;
  67. return 1;
  68. }
  69. return 0;
  70. }
  71. //]
  72. #include <boost/interprocess/detail/config_end.hpp>