Mutex.h 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/Assertions.h>
  8. #include <AK/Types.h>
  9. #include <pthread.h>
  10. namespace Threading {
  11. class Mutex {
  12. AK_MAKE_NONCOPYABLE(Mutex);
  13. AK_MAKE_NONMOVABLE(Mutex);
  14. friend class ConditionVariable;
  15. public:
  16. Mutex()
  17. {
  18. #ifndef __serenity__
  19. pthread_mutexattr_t attr;
  20. pthread_mutexattr_init(&attr);
  21. pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
  22. pthread_mutex_init(&m_mutex, &attr);
  23. #endif
  24. }
  25. ~Mutex() = default;
  26. void lock();
  27. void unlock();
  28. private:
  29. #ifdef __serenity__
  30. pthread_mutex_t m_mutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
  31. #else
  32. pthread_mutex_t m_mutex;
  33. #endif
  34. };
  35. class MutexLocker {
  36. AK_MAKE_NONCOPYABLE(MutexLocker);
  37. AK_MAKE_NONMOVABLE(MutexLocker);
  38. public:
  39. ALWAYS_INLINE explicit MutexLocker(Mutex& mutex)
  40. : m_mutex(mutex)
  41. {
  42. lock();
  43. }
  44. ALWAYS_INLINE ~MutexLocker() { unlock(); }
  45. ALWAYS_INLINE void unlock() { m_mutex.unlock(); }
  46. ALWAYS_INLINE void lock() { m_mutex.lock(); }
  47. private:
  48. Mutex& m_mutex;
  49. };
  50. ALWAYS_INLINE void Mutex::lock()
  51. {
  52. pthread_mutex_lock(&m_mutex);
  53. }
  54. ALWAYS_INLINE void Mutex::unlock()
  55. {
  56. pthread_mutex_unlock(&m_mutex);
  57. }
  58. }