Mutex.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Mutex.h"
  25. #ifdef _WIN32
  26. #include <Windows.h>
  27. #else
  28. #include <pthread.h>
  29. #endif
  30. #include "DebugNew.h"
  31. #ifdef _WIN32
  32. Mutex::Mutex() :
  33. criticalSection_(new CRITICAL_SECTION)
  34. {
  35. InitializeCriticalSection((CRITICAL_SECTION*)criticalSection_);
  36. }
  37. Mutex::~Mutex()
  38. {
  39. CRITICAL_SECTION* cs = (CRITICAL_SECTION*)criticalSection_;
  40. DeleteCriticalSection(cs);
  41. delete cs;
  42. criticalSection_ = 0;
  43. }
  44. void Mutex::Acquire()
  45. {
  46. EnterCriticalSection((CRITICAL_SECTION*)criticalSection_);
  47. }
  48. void Mutex::Release()
  49. {
  50. LeaveCriticalSection((CRITICAL_SECTION*)criticalSection_);
  51. }
  52. #else
  53. Mutex::Mutex() :
  54. criticalSection_(new pthread_mutex_t)
  55. {
  56. pthread_mutex_init((pthread_mutex_t*)criticalSection_);
  57. }
  58. Mutex::~Mutex()
  59. {
  60. pthread_mutex_t* mutex = (pthread_mutex_t*)criticalSection_;
  61. pthread_mutex_destroy(mutex);
  62. delete mutex;
  63. criticalSection_ = 0;
  64. }
  65. void Mutex::Acquire()
  66. {
  67. pthread_mutex_lock((pthread_mutex_t*)criticalSection_);
  68. }
  69. void Mutex::Release()
  70. {
  71. pthread_mutex_acquire((pthread_mutex_t*)criticalSection_);
  72. }
  73. #endif
  74. MutexLock::MutexLock(Mutex& mutex) :
  75. mutex_(mutex)
  76. {
  77. mutex_.Acquire();
  78. }
  79. MutexLock::~MutexLock()
  80. {
  81. mutex_.Release();
  82. }