Mutex.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, kleines Filmröllchen <malu.bertsch@gmail.com>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #pragma once
  8. #include <AK/Assertions.h>
  9. #include <AK/Format.h>
  10. #include <AK/Noncopyable.h>
  11. #include <AK/Types.h>
  12. #include <pthread.h>
  13. namespace Threading {
  14. class Mutex {
  15. AK_MAKE_NONCOPYABLE(Mutex);
  16. AK_MAKE_NONMOVABLE(Mutex);
  17. friend class ConditionVariable;
  18. public:
  19. Mutex()
  20. : m_lock_count(0)
  21. {
  22. #ifndef __serenity__
  23. pthread_mutexattr_t attr;
  24. pthread_mutexattr_init(&attr);
  25. pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
  26. pthread_mutex_init(&m_mutex, &attr);
  27. #endif
  28. }
  29. ~Mutex()
  30. {
  31. VERIFY(m_lock_count == 0);
  32. // FIXME: pthread_mutex_destroy() is not implemented.
  33. }
  34. void lock();
  35. void unlock();
  36. private:
  37. #ifdef __serenity__
  38. pthread_mutex_t m_mutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
  39. #else
  40. pthread_mutex_t m_mutex;
  41. #endif
  42. unsigned m_lock_count { 0 };
  43. };
  44. class MutexLocker {
  45. AK_MAKE_NONCOPYABLE(MutexLocker);
  46. AK_MAKE_NONMOVABLE(MutexLocker);
  47. public:
  48. ALWAYS_INLINE explicit MutexLocker(Mutex& mutex)
  49. : m_mutex(mutex)
  50. {
  51. lock();
  52. }
  53. ALWAYS_INLINE ~MutexLocker()
  54. {
  55. unlock();
  56. }
  57. ALWAYS_INLINE void unlock() { m_mutex.unlock(); }
  58. ALWAYS_INLINE void lock() { m_mutex.lock(); }
  59. private:
  60. Mutex& m_mutex;
  61. };
  62. ALWAYS_INLINE void Mutex::lock()
  63. {
  64. pthread_mutex_lock(&m_mutex);
  65. m_lock_count++;
  66. }
  67. ALWAYS_INLINE void Mutex::unlock()
  68. {
  69. VERIFY(m_lock_count > 0);
  70. // FIXME: We need to protect the lock count with the mutex itself.
  71. // This may be bad because we're not *technically* unlocked yet,
  72. // but we're not handling any errors from pthread_mutex_unlock anyways.
  73. m_lock_count--;
  74. pthread_mutex_unlock(&m_mutex);
  75. }
  76. }