comp_doc_anonymous_conditionB.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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_conditionB
  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 <cstring>
  17. #include "doc_anonymous_condition_shared_data.hpp"
  18. using namespace boost::interprocess;
  19. int main ()
  20. {
  21. //Create a shared memory object.
  22. shared_memory_object shm
  23. (open_only //only create
  24. ,"MySharedMemory" //name
  25. ,read_write //read-write mode
  26. );
  27. try{
  28. //Map the whole shared memory in this process
  29. mapped_region region
  30. (shm //What to map
  31. ,read_write //Map it as read-write
  32. );
  33. //Get the address of the mapped region
  34. void * addr = region.get_address();
  35. //Obtain a pointer to the shared structure
  36. trace_queue * data = static_cast<trace_queue*>(addr);
  37. //Print messages until the other process marks the end
  38. bool end_loop = false;
  39. do{
  40. scoped_lock<interprocess_mutex> lock(data->mutex);
  41. if(!data->message_in){
  42. data->cond_empty.wait(lock);
  43. }
  44. if(std::strcmp(data->items, "last message") == 0){
  45. end_loop = true;
  46. }
  47. else{
  48. //Print the message
  49. std::cout << data->items << std::endl;
  50. //Notify the other process that the buffer is empty
  51. data->message_in = false;
  52. data->cond_full.notify_one();
  53. }
  54. }
  55. while(!end_loop);
  56. }
  57. catch(interprocess_exception &ex){
  58. std::cout << ex.what() << std::endl;
  59. return 1;
  60. }
  61. return 0;
  62. }
  63. //]
  64. #include <boost/interprocess/detail/config_end.hpp>