mutex.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. /*
  2. * Copyright 2010-2018 Branimir Karadzic. All rights reserved.
  3. * License: https://github.com/bkaradzic/bx#license-bsd-2-clause
  4. */
  5. #include "bx_p.h"
  6. #include <bx/mutex.h>
  7. #if BX_CONFIG_SUPPORTS_THREADING
  8. #if BX_PLATFORM_ANDROID \
  9. || BX_PLATFORM_LINUX \
  10. || BX_PLATFORM_IOS \
  11. || BX_PLATFORM_OSX \
  12. || BX_PLATFORM_PS4 \
  13. || BX_PLATFORM_RPI
  14. # include <pthread.h>
  15. #elif BX_PLATFORM_WINDOWS \
  16. || BX_PLATFORM_WINRT \
  17. || BX_PLATFORM_XBOXONE
  18. # include <windows.h>
  19. # include <errno.h>
  20. #endif // BX_PLATFORM_
  21. namespace bx
  22. {
  23. #if BX_PLATFORM_WINDOWS \
  24. || BX_PLATFORM_XBOXONE \
  25. || BX_PLATFORM_WINRT
  26. typedef CRITICAL_SECTION pthread_mutex_t;
  27. typedef unsigned pthread_mutexattr_t;
  28. inline int pthread_mutex_lock(pthread_mutex_t* _mutex)
  29. {
  30. EnterCriticalSection(_mutex);
  31. return 0;
  32. }
  33. inline int pthread_mutex_unlock(pthread_mutex_t* _mutex)
  34. {
  35. LeaveCriticalSection(_mutex);
  36. return 0;
  37. }
  38. inline int pthread_mutex_trylock(pthread_mutex_t* _mutex)
  39. {
  40. return TryEnterCriticalSection(_mutex) ? 0 : EBUSY;
  41. }
  42. inline int pthread_mutex_init(pthread_mutex_t* _mutex, pthread_mutexattr_t* /*_attr*/)
  43. {
  44. #if BX_PLATFORM_WINRT
  45. InitializeCriticalSectionEx(_mutex, 4000, 0); // docs recommend 4000 spincount as sane default
  46. #else
  47. InitializeCriticalSection(_mutex);
  48. #endif // BX_PLATFORM_
  49. return 0;
  50. }
  51. inline int pthread_mutex_destroy(pthread_mutex_t* _mutex)
  52. {
  53. DeleteCriticalSection(_mutex);
  54. return 0;
  55. }
  56. #endif // BX_PLATFORM_
  57. Mutex::Mutex()
  58. {
  59. BX_STATIC_ASSERT(sizeof(pthread_mutex_t) <= sizeof(m_internal) );
  60. pthread_mutexattr_t attr;
  61. #if BX_PLATFORM_WINDOWS \
  62. || BX_PLATFORM_XBOXONE \
  63. || BX_PLATFORM_WINRT
  64. #else
  65. pthread_mutexattr_init(&attr);
  66. pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
  67. #endif // BX_PLATFORM_
  68. pthread_mutex_t* handle = (pthread_mutex_t*)m_internal;
  69. pthread_mutex_init(handle, &attr);
  70. }
  71. Mutex::~Mutex()
  72. {
  73. pthread_mutex_t* handle = (pthread_mutex_t*)m_internal;
  74. pthread_mutex_destroy(handle);
  75. }
  76. void Mutex::lock()
  77. {
  78. pthread_mutex_t* handle = (pthread_mutex_t*)m_internal;
  79. pthread_mutex_lock(handle);
  80. }
  81. void Mutex::unlock()
  82. {
  83. pthread_mutex_t* handle = (pthread_mutex_t*)m_internal;
  84. pthread_mutex_unlock(handle);
  85. }
  86. } // namespace bx
  87. #endif // BX_MUTEX_H_HEADER_GUARD