interprocess_sync.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright (C) 2012 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. // PERFORMANCE OF THIS SOFTWARE.
  14. #ifndef __INTERPROCESS_SYNC_H__
  15. #define __INTERPROCESS_SYNC_H__
  16. #include <string>
  17. namespace isc {
  18. namespace util {
  19. class InterprocessSyncLocker;
  20. class InterprocessSync {
  21. friend class InterprocessSyncLocker;
  22. public:
  23. /// \brief Constructor
  24. ///
  25. /// Creates a interprocess synchronization object
  26. InterprocessSync(const std::string& component_name) :
  27. component_name_(component_name), is_locked_(false)
  28. {}
  29. /// \brief Destructor
  30. virtual ~InterprocessSync() {}
  31. protected:
  32. virtual bool lock() = 0;
  33. virtual bool tryLock() = 0;
  34. virtual bool unlock() = 0;
  35. const std::string component_name_;
  36. bool is_locked_;
  37. };
  38. class InterprocessSyncLocker {
  39. public:
  40. InterprocessSyncLocker(InterprocessSync& sync) :
  41. sync_(sync)
  42. {}
  43. /// \brief Destructor
  44. ~InterprocessSyncLocker() {
  45. unlock();
  46. }
  47. bool lock() {
  48. return (sync_.lock());
  49. }
  50. bool tryLock() {
  51. return (sync_.tryLock());
  52. }
  53. bool unlock() {
  54. return (sync_.unlock());
  55. }
  56. protected:
  57. InterprocessSync& sync_;
  58. };
  59. } // namespace util
  60. } // namespace isc
  61. #endif // __INTERPROCESS_SYNC_H__