Interprocess.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /*
  2. * Interprocess.h, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #pragma once
  11. #include <boost/interprocess/sync/scoped_lock.hpp>
  12. #include <boost/interprocess/sync/interprocess_mutex.hpp>
  13. #include <boost/interprocess/sync/interprocess_condition.hpp>
  14. #include <boost/interprocess/mapped_region.hpp>
  15. #include <boost/interprocess/shared_memory_object.hpp>
  16. VCMI_LIB_NAMESPACE_BEGIN
  17. struct ServerReady
  18. {
  19. bool ready;
  20. uint16_t port; //ui16?
  21. boost::interprocess::interprocess_mutex mutex;
  22. boost::interprocess::interprocess_condition cond;
  23. ServerReady()
  24. {
  25. ready = false;
  26. port = 0;
  27. }
  28. void waitTillReady()
  29. {
  30. boost::interprocess::scoped_lock<boost::interprocess::interprocess_mutex> slock(mutex);
  31. while(!ready)
  32. {
  33. cond.wait(slock);
  34. }
  35. }
  36. void setToReadyAndNotify(const uint16_t Port)
  37. {
  38. {
  39. boost::unique_lock<boost::interprocess::interprocess_mutex> lock(mutex);
  40. ready = true;
  41. port = Port;
  42. }
  43. cond.notify_all();
  44. }
  45. };
  46. struct SharedMemory
  47. {
  48. std::string name;
  49. boost::interprocess::shared_memory_object smo;
  50. boost::interprocess::mapped_region * mr;
  51. ServerReady * sr;
  52. SharedMemory(const std::string & Name, bool initialize = false)
  53. : name(Name)
  54. {
  55. if(initialize)
  56. {
  57. //if the application has previously crashed, the memory may not have been removed. to avoid problems - try to destroy it
  58. boost::interprocess::shared_memory_object::remove(name.c_str());
  59. }
  60. smo = boost::interprocess::shared_memory_object(boost::interprocess::open_or_create, name.c_str(), boost::interprocess::read_write);
  61. smo.truncate(sizeof(ServerReady));
  62. mr = new boost::interprocess::mapped_region(smo,boost::interprocess::read_write);
  63. if(initialize)
  64. sr = new(mr->get_address())ServerReady();
  65. else
  66. sr = reinterpret_cast<ServerReady*>(mr->get_address());
  67. };
  68. ~SharedMemory()
  69. {
  70. delete mr;
  71. boost::interprocess::shared_memory_object::remove(name.c_str());
  72. }
  73. };
  74. VCMI_LIB_NAMESPACE_END