comp_doc_anonymous_conditionA.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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_conditionA
  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 <iostream>
  16. #include <cstdio>
  17. #include "doc_anonymous_condition_shared_data.hpp"
  18. using namespace boost::interprocess;
  19. int main ()
  20. {
  21. //Erase previous shared memory and schedule erasure on exit
  22. struct shm_remove
  23. {
  24. shm_remove() { shared_memory_object::remove("MySharedMemory"); }
  25. ~shm_remove(){ shared_memory_object::remove("MySharedMemory"); }
  26. } remover;
  27. //<-
  28. (void)remover;
  29. //->
  30. //Create a shared memory object.
  31. shared_memory_object shm
  32. (create_only //only create
  33. ,"MySharedMemory" //name
  34. ,read_write //read-write mode
  35. );
  36. try{
  37. //Set size
  38. shm.truncate(sizeof(trace_queue));
  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. trace_queue * data = new (addr) trace_queue;
  48. const int NumMsg = 100;
  49. for(int i = 0; i < NumMsg; ++i){
  50. scoped_lock<interprocess_mutex> lock(data->mutex);
  51. if(data->message_in){
  52. data->cond_full.wait(lock);
  53. }
  54. if(i == (NumMsg-1))
  55. std::sprintf(data->items, "%s", "last message");
  56. else
  57. std::sprintf(data->items, "%s_%d", "my_trace", i);
  58. //Notify to the other process that there is a message
  59. data->cond_empty.notify_one();
  60. //Mark message buffer as full
  61. data->message_in = true;
  62. }
  63. }
  64. catch(interprocess_exception &ex){
  65. std::cout << ex.what() << std::endl;
  66. return 1;
  67. }
  68. return 0;
  69. }
  70. //]