Mutex.cpp 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. // Copyright (c) 2008-2023 the Urho3D project
  2. // License: MIT
  3. #include "../Precompiled.h"
  4. #include "../Core/Mutex.h"
  5. #ifdef _WIN32
  6. #include "../Engine/WinWrapped.h"
  7. #else
  8. #include <pthread.h>
  9. #endif
  10. #include "../DebugNew.h"
  11. namespace Urho3D
  12. {
  13. #ifdef _WIN32
  14. Mutex::Mutex() :
  15. handle_(new CRITICAL_SECTION)
  16. {
  17. InitializeCriticalSection((CRITICAL_SECTION*)handle_);
  18. }
  19. Mutex::~Mutex()
  20. {
  21. CRITICAL_SECTION* cs = (CRITICAL_SECTION*)handle_;
  22. DeleteCriticalSection(cs);
  23. delete cs;
  24. handle_ = nullptr;
  25. }
  26. void Mutex::Acquire()
  27. {
  28. EnterCriticalSection((CRITICAL_SECTION*)handle_);
  29. }
  30. bool Mutex::TryAcquire()
  31. {
  32. return TryEnterCriticalSection((CRITICAL_SECTION*)handle_) != FALSE;
  33. }
  34. void Mutex::Release()
  35. {
  36. LeaveCriticalSection((CRITICAL_SECTION*)handle_);
  37. }
  38. #else
  39. Mutex::Mutex() :
  40. handle_(new pthread_mutex_t)
  41. {
  42. auto* mutex = (pthread_mutex_t*)handle_;
  43. pthread_mutexattr_t attr;
  44. pthread_mutexattr_init(&attr);
  45. pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
  46. pthread_mutex_init(mutex, &attr);
  47. }
  48. Mutex::~Mutex()
  49. {
  50. auto* mutex = (pthread_mutex_t*)handle_;
  51. pthread_mutex_destroy(mutex);
  52. delete mutex;
  53. handle_ = nullptr;
  54. }
  55. void Mutex::Acquire()
  56. {
  57. pthread_mutex_lock((pthread_mutex_t*)handle_);
  58. }
  59. bool Mutex::TryAcquire()
  60. {
  61. return pthread_mutex_trylock((pthread_mutex_t*)handle_) == 0;
  62. }
  63. void Mutex::Release()
  64. {
  65. pthread_mutex_unlock((pthread_mutex_t*)handle_);
  66. }
  67. #endif
  68. MutexLock::MutexLock(Mutex& mutex) :
  69. mutex_(mutex)
  70. {
  71. mutex_.Acquire();
  72. }
  73. MutexLock::~MutexLock()
  74. {
  75. mutex_.Release();
  76. }
  77. }