ScopedLock.h 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. //
  2. // ScopedLock.h
  3. //
  4. // Library: Foundation
  5. // Package: Threading
  6. // Module: Mutex
  7. //
  8. // Definition of the ScopedLock template class.
  9. //
  10. // Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
  11. // and Contributors.
  12. //
  13. // SPDX-License-Identifier: BSL-1.0
  14. //
  15. #ifndef Foundation_ScopedLock_INCLUDED
  16. #define Foundation_ScopedLock_INCLUDED
  17. #include "Poco/Foundation.h"
  18. namespace Poco {
  19. template <class M>
  20. class ScopedLock
  21. /// A class that simplifies thread synchronization
  22. /// with a mutex.
  23. /// The constructor accepts a Mutex (and optionally
  24. /// a timeout value in milliseconds) and locks it.
  25. /// The destructor unlocks the mutex.
  26. {
  27. public:
  28. explicit ScopedLock(M& mutex): _mutex(mutex)
  29. {
  30. _mutex.lock();
  31. }
  32. ScopedLock(M& mutex, long milliseconds): _mutex(mutex)
  33. {
  34. _mutex.lock(milliseconds);
  35. }
  36. ~ScopedLock()
  37. {
  38. try
  39. {
  40. _mutex.unlock();
  41. }
  42. catch (...)
  43. {
  44. poco_unexpected();
  45. }
  46. }
  47. private:
  48. M& _mutex;
  49. ScopedLock();
  50. ScopedLock(const ScopedLock&);
  51. ScopedLock& operator = (const ScopedLock&);
  52. };
  53. template <class M>
  54. class ScopedLockWithUnlock
  55. /// A class that simplifies thread synchronization
  56. /// with a mutex.
  57. /// The constructor accepts a Mutex (and optionally
  58. /// a timeout value in milliseconds) and locks it.
  59. /// The destructor unlocks the mutex.
  60. /// The unlock() member function allows for manual
  61. /// unlocking of the mutex.
  62. {
  63. public:
  64. explicit ScopedLockWithUnlock(M& mutex): _pMutex(&mutex)
  65. {
  66. _pMutex->lock();
  67. }
  68. ScopedLockWithUnlock(M& mutex, long milliseconds): _pMutex(&mutex)
  69. {
  70. _pMutex->lock(milliseconds);
  71. }
  72. ~ScopedLockWithUnlock()
  73. {
  74. try
  75. {
  76. unlock();
  77. }
  78. catch (...)
  79. {
  80. poco_unexpected();
  81. }
  82. }
  83. void unlock()
  84. {
  85. if (_pMutex)
  86. {
  87. _pMutex->unlock();
  88. _pMutex = 0;
  89. }
  90. }
  91. private:
  92. M* _pMutex;
  93. ScopedLockWithUnlock();
  94. ScopedLockWithUnlock(const ScopedLockWithUnlock&);
  95. ScopedLockWithUnlock& operator = (const ScopedLockWithUnlock&);
  96. };
  97. } // namespace Poco
  98. #endif // Foundation_ScopedLock_INCLUDED