mutex.cpp 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Copyright 2009-2021 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. }
  34. void MutexSys::lock()
  35. {
  36. if (pthread_mutex_lock((pthread_mutex_t*)mutex) != 0)
  37. THROW_RUNTIME_ERROR("pthread_mutex_lock failed");
  38. }
  39. bool MutexSys::try_lock() {
  40. return pthread_mutex_trylock((pthread_mutex_t*)mutex) == 0;
  41. }
  42. void MutexSys::unlock()
  43. {
  44. if (pthread_mutex_unlock((pthread_mutex_t*)mutex) != 0)
  45. THROW_RUNTIME_ERROR("pthread_mutex_unlock failed");
  46. }
  47. };
  48. #endif