Mutex.h 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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/Noncopyable.h>
  9. #include <AK/Types.h>
  10. #include <pthread.h>
  11. namespace Threading {
  12. class Mutex {
  13. AK_MAKE_NONCOPYABLE(Mutex);
  14. AK_MAKE_NONMOVABLE(Mutex);
  15. friend class ConditionVariable;
  16. public:
  17. Mutex()
  18. {
  19. #ifndef __serenity__
  20. pthread_mutexattr_t attr;
  21. pthread_mutexattr_init(&attr);
  22. pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
  23. pthread_mutex_init(&m_mutex, &attr);
  24. #endif
  25. }
  26. ~Mutex() = default;
  27. void lock();
  28. void unlock();
  29. private:
  30. #ifdef __serenity__
  31. pthread_mutex_t m_mutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
  32. #else
  33. pthread_mutex_t m_mutex;
  34. #endif
  35. };
  36. class MutexLocker {
  37. AK_MAKE_NONCOPYABLE(MutexLocker);
  38. AK_MAKE_NONMOVABLE(MutexLocker);
  39. public:
  40. ALWAYS_INLINE explicit MutexLocker(Mutex& mutex)
  41. : m_mutex(mutex)
  42. {
  43. lock();
  44. }
  45. ALWAYS_INLINE ~MutexLocker() { unlock(); }
  46. ALWAYS_INLINE void unlock() { m_mutex.unlock(); }
  47. ALWAYS_INLINE void lock() { m_mutex.lock(); }
  48. private:
  49. Mutex& m_mutex;
  50. };
  51. ALWAYS_INLINE void Mutex::lock()
  52. {
  53. pthread_mutex_lock(&m_mutex);
  54. }
  55. ALWAYS_INLINE void Mutex::unlock()
  56. {
  57. pthread_mutex_unlock(&m_mutex);
  58. }
  59. }