comp_doc_anonymous_semaphoreA.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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_semaphoreA
  12. #include <boost/interprocess/shared_memory_object.hpp>
  13. #include <boost/interprocess/mapped_region.hpp>
  14. #include <iostream>
  15. #include "doc_anonymous_semaphore_shared_data.hpp"
  16. using namespace boost::interprocess;
  17. int main ()
  18. {
  19. //Remove shared memory on construction and destruction
  20. struct shm_remove
  21. {
  22. shm_remove() { shared_memory_object::remove("MySharedMemory"); }
  23. ~shm_remove(){ shared_memory_object::remove("MySharedMemory"); }
  24. } remover;
  25. //<-
  26. (void)remover;
  27. //->
  28. //Create a shared memory object.
  29. shared_memory_object shm
  30. (create_only //only create
  31. ,"MySharedMemory" //name
  32. ,read_write //read-write mode
  33. );
  34. //Set size
  35. shm.truncate(sizeof(shared_memory_buffer));
  36. //Map the whole shared memory in this process
  37. mapped_region region
  38. (shm //What to map
  39. ,read_write //Map it as read-write
  40. );
  41. //Get the address of the mapped region
  42. void * addr = region.get_address();
  43. //Construct the shared structure in memory
  44. shared_memory_buffer * data = new (addr) shared_memory_buffer;
  45. const int NumMsg = 100;
  46. //Insert data in the array
  47. for(int i = 0; i < NumMsg; ++i){
  48. data->nempty.wait();
  49. data->mutex.wait();
  50. data->items[i % shared_memory_buffer::NumItems] = i;
  51. data->mutex.post();
  52. data->nstored.post();
  53. }
  54. return 0;
  55. }
  56. //]
  57. #include <boost/interprocess/detail/config_end.hpp>