mutex.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Copyright 2009-2020 Intel Corporation
  2. // SPDX-License-Identifier: Apache-2.0
  3. #include "mutex.h"
  4. #include "regression.h"
  5. #if defined(__WIN32__) && !defined(PTHREADS_WIN32)
  6. #define WIN32_LEAN_AND_MEAN
  7. #include <windows.h>
  8. namespace embree
  9. {
  10. MutexSys::MutexSys() { mutex = new CRITICAL_SECTION; InitializeCriticalSection((CRITICAL_SECTION*)mutex); }
  11. MutexSys::~MutexSys() { DeleteCriticalSection((CRITICAL_SECTION*)mutex); delete (CRITICAL_SECTION*)mutex; }
  12. void MutexSys::lock() { EnterCriticalSection((CRITICAL_SECTION*)mutex); }
  13. bool MutexSys::try_lock() { return TryEnterCriticalSection((CRITICAL_SECTION*)mutex) != 0; }
  14. void MutexSys::unlock() { LeaveCriticalSection((CRITICAL_SECTION*)mutex); }
  15. }
  16. #endif
  17. #if defined(__UNIX__) || defined(PTHREADS_WIN32)
  18. #include <pthread.h>
  19. namespace embree
  20. {
  21. /*! system mutex using pthreads */
  22. MutexSys::MutexSys()
  23. {
  24. mutex = new pthread_mutex_t;
  25. if (pthread_mutex_init((pthread_mutex_t*)mutex, nullptr) != 0)
  26. THROW_RUNTIME_ERROR("pthread_mutex_init failed");
  27. }
  28. MutexSys::~MutexSys()
  29. {
  30. MAYBE_UNUSED bool ok = pthread_mutex_destroy((pthread_mutex_t*)mutex) == 0;
  31. assert(ok);
  32. delete (pthread_mutex_t*)mutex;
  33. mutex = nullptr;
  34. }
  35. void MutexSys::lock()
  36. {
  37. if (pthread_mutex_lock((pthread_mutex_t*)mutex) != 0)
  38. THROW_RUNTIME_ERROR("pthread_mutex_lock failed");
  39. }
  40. bool MutexSys::try_lock() {
  41. return pthread_mutex_trylock((pthread_mutex_t*)mutex) == 0;
  42. }
  43. void MutexSys::unlock()
  44. {
  45. if (pthread_mutex_unlock((pthread_mutex_t*)mutex) != 0)
  46. THROW_RUNTIME_ERROR("pthread_mutex_unlock failed");
  47. }
  48. };
  49. #endif