Mutex_POSIX.h 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. //
  2. // Mutex_POSIX.h
  3. //
  4. // Library: Foundation
  5. // Package: Threading
  6. // Module: Mutex
  7. //
  8. // Definition of the MutexImpl and FastMutexImpl classes for POSIX Threads.
  9. //
  10. // Copyright (c) 2004-2008, Applied Informatics Software Engineering GmbH.
  11. // and Contributors.
  12. //
  13. // SPDX-License-Identifier: BSL-1.0
  14. //
  15. #ifndef Foundation_Mutex_POSIX_INCLUDED
  16. #define Foundation_Mutex_POSIX_INCLUDED
  17. #include "Poco/Foundation.h"
  18. #include "Poco/Exception.h"
  19. #include <pthread.h>
  20. #include <errno.h>
  21. namespace Poco {
  22. class Foundation_API MutexImpl
  23. {
  24. protected:
  25. MutexImpl();
  26. MutexImpl(bool fast);
  27. ~MutexImpl();
  28. void lockImpl();
  29. bool tryLockImpl();
  30. bool tryLockImpl(long milliseconds);
  31. void unlockImpl();
  32. private:
  33. pthread_mutex_t _mutex;
  34. };
  35. class Foundation_API FastMutexImpl: public MutexImpl
  36. {
  37. protected:
  38. FastMutexImpl();
  39. ~FastMutexImpl();
  40. };
  41. //
  42. // inlines
  43. //
  44. inline void MutexImpl::lockImpl()
  45. {
  46. if (pthread_mutex_lock(&_mutex))
  47. throw SystemException("cannot lock mutex");
  48. }
  49. inline bool MutexImpl::tryLockImpl()
  50. {
  51. int rc = pthread_mutex_trylock(&_mutex);
  52. if (rc == 0)
  53. return true;
  54. else if (rc == EBUSY)
  55. return false;
  56. else
  57. throw SystemException("cannot lock mutex");
  58. }
  59. inline void MutexImpl::unlockImpl()
  60. {
  61. if (pthread_mutex_unlock(&_mutex))
  62. throw SystemException("cannot unlock mutex");
  63. }
  64. } // namespace Poco
  65. #endif // Foundation_Mutex_POSIX_INCLUDED