Mutex.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. #pragma once
  2. #include "os/ErrorCodes.h"
  3. #include "os/Handle.h"
  4. #include "os/WaitStatus.h"
  5. #include "utils/NonCopyable.h"
  6. namespace il2cpp
  7. {
  8. namespace os
  9. {
  10. class MutexImpl;
  11. class FastMutexImpl;
  12. class Mutex : public il2cpp::utils::NonCopyable
  13. {
  14. public:
  15. Mutex(bool initiallyOwned = false);
  16. ~Mutex();
  17. void Lock(bool interruptible = false);
  18. bool TryLock(uint32_t milliseconds = 0, bool interruptible = false);
  19. void Unlock();
  20. private:
  21. MutexImpl* m_Mutex;
  22. };
  23. struct AutoLock : public il2cpp::utils::NonCopyable
  24. {
  25. AutoLock(Mutex* mutex) : m_Mutex(mutex) { m_Mutex->Lock(); }
  26. ~AutoLock() { m_Mutex->Unlock(); }
  27. private:
  28. Mutex* m_Mutex;
  29. };
  30. class MutexHandle : public Handle
  31. {
  32. public:
  33. MutexHandle(Mutex* mutex) : m_Mutex(mutex) {}
  34. virtual ~MutexHandle() { delete m_Mutex; }
  35. virtual bool Wait() { m_Mutex->Lock(true); return true; }
  36. virtual bool Wait(uint32_t ms) { return m_Mutex->TryLock(ms, true); }
  37. virtual WaitStatus Wait(bool interruptible) { m_Mutex->Lock(interruptible); return kWaitStatusSuccess; }
  38. virtual WaitStatus Wait(uint32_t ms, bool interruptible) { return m_Mutex->TryLock(ms, interruptible) ? kWaitStatusSuccess : kWaitStatusFailure; }
  39. virtual void Signal() { m_Mutex->Unlock(); }
  40. Mutex* Get() { return m_Mutex; }
  41. private:
  42. Mutex* m_Mutex;
  43. };
  44. /// Lightweight mutex that has no support for interruption or timed waits. Meant for
  45. /// internal use only.
  46. class FastMutex
  47. {
  48. public:
  49. FastMutex();
  50. ~FastMutex();
  51. void Lock();
  52. void Unlock();
  53. FastMutexImpl* GetImpl();
  54. private:
  55. FastMutexImpl* m_Impl;
  56. };
  57. struct FastAutoLock : public il2cpp::utils::NonCopyable
  58. {
  59. FastAutoLock(FastMutex* mutex)
  60. : m_Mutex(mutex)
  61. {
  62. m_Mutex->Lock();
  63. }
  64. ~FastAutoLock()
  65. {
  66. m_Mutex->Unlock();
  67. }
  68. private:
  69. FastMutex* m_Mutex;
  70. };
  71. struct FastAutoUnlock : public il2cpp::utils::NonCopyable
  72. {
  73. FastAutoUnlock(FastMutex* mutex)
  74. : m_Mutex(mutex)
  75. {
  76. m_Mutex->Unlock();
  77. }
  78. ~FastAutoUnlock()
  79. {
  80. m_Mutex->Lock();
  81. }
  82. private:
  83. FastMutex* m_Mutex;
  84. };
  85. }
  86. }