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