mutex.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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_XBOX360 \
  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 || BX_PLATFORM_XBOX360 || BX_PLATFORM_XBOXONE || BX_PLATFORM_WINRT
  24. typedef CRITICAL_SECTION pthread_mutex_t;
  25. typedef unsigned pthread_mutexattr_t;
  26. inline int pthread_mutex_lock(pthread_mutex_t* _mutex)
  27. {
  28. EnterCriticalSection(_mutex);
  29. return 0;
  30. }
  31. inline int pthread_mutex_unlock(pthread_mutex_t* _mutex)
  32. {
  33. LeaveCriticalSection(_mutex);
  34. return 0;
  35. }
  36. inline int pthread_mutex_trylock(pthread_mutex_t* _mutex)
  37. {
  38. return TryEnterCriticalSection(_mutex) ? 0 : EBUSY;
  39. }
  40. inline int pthread_mutex_init(pthread_mutex_t* _mutex, pthread_mutexattr_t* /*_attr*/)
  41. {
  42. #if BX_PLATFORM_WINRT
  43. InitializeCriticalSectionEx(_mutex, 4000, 0); // docs recommend 4000 spincount as sane default
  44. #else
  45. InitializeCriticalSection(_mutex);
  46. #endif // BX_PLATFORM_
  47. return 0;
  48. }
  49. inline int pthread_mutex_destroy(pthread_mutex_t* _mutex)
  50. {
  51. DeleteCriticalSection(_mutex);
  52. return 0;
  53. }
  54. #endif // BX_PLATFORM_
  55. Mutex::Mutex()
  56. {
  57. BX_STATIC_ASSERT(sizeof(pthread_mutex_t) <= sizeof(m_internal) );
  58. pthread_mutexattr_t attr;
  59. #if BX_PLATFORM_WINDOWS || BX_PLATFORM_XBOX360 || BX_PLATFORM_XBOXONE || BX_PLATFORM_WINRT
  60. #else
  61. pthread_mutexattr_init(&attr);
  62. pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
  63. #endif // BX_PLATFORM_
  64. pthread_mutex_t* handle = (pthread_mutex_t*)m_internal;
  65. pthread_mutex_init(handle, &attr);
  66. }
  67. Mutex::~Mutex()
  68. {
  69. pthread_mutex_t* handle = (pthread_mutex_t*)m_internal;
  70. pthread_mutex_destroy(handle);
  71. }
  72. void Mutex::lock()
  73. {
  74. pthread_mutex_t* handle = (pthread_mutex_t*)m_internal;
  75. pthread_mutex_lock(handle);
  76. }
  77. void Mutex::unlock()
  78. {
  79. pthread_mutex_t* handle = (pthread_mutex_t*)m_internal;
  80. pthread_mutex_unlock(handle);
  81. }
  82. } // namespace bx
  83. #endif // BX_MUTEX_H_HEADER_GUARD