mutex.cpp 2.2 KB

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