ScopedUnlock.h 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. //
  2. // ScopedUnlock.h
  3. //
  4. // $Id: //poco/1.4/Foundation/include/Poco/ScopedUnlock.h#1 $
  5. //
  6. // Library: Foundation
  7. // Package: Threading
  8. // Module: Mutex
  9. //
  10. // Definition of the ScopedUnlock template class.
  11. //
  12. // Copyright (c) 2007, Applied Informatics Software Engineering GmbH.
  13. // and Contributors.
  14. //
  15. // SPDX-License-Identifier: BSL-1.0
  16. //
  17. #ifndef Foundation_ScopedUnlock_INCLUDED
  18. #define Foundation_ScopedUnlock_INCLUDED
  19. #include "Poco/Foundation.h"
  20. namespace Poco {
  21. template <class M>
  22. class ScopedUnlock
  23. /// A class that simplifies thread synchronization
  24. /// with a mutex.
  25. /// The constructor accepts a Mutex and unlocks it.
  26. /// The destructor locks the mutex.
  27. {
  28. public:
  29. inline ScopedUnlock(M& mutex, bool unlockNow = true): _mutex(mutex)
  30. {
  31. if (unlockNow)
  32. _mutex.unlock();
  33. }
  34. inline ~ScopedUnlock()
  35. {
  36. try
  37. {
  38. _mutex.lock();
  39. }
  40. catch (...)
  41. {
  42. poco_unexpected();
  43. }
  44. }
  45. private:
  46. M& _mutex;
  47. ScopedUnlock();
  48. ScopedUnlock(const ScopedUnlock&);
  49. ScopedUnlock& operator = (const ScopedUnlock&);
  50. };
  51. } // namespace Poco
  52. #endif // Foundation_ScopedUnlock_INCLUDED