-
Notifications
You must be signed in to change notification settings - Fork 182
/
Mutex.cpp
104 lines (68 loc) · 2.03 KB
/
Mutex.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/***************************************************/
/*! \class Mutex
\brief STK mutex class.
This class provides a uniform interface for
cross-platform mutex use. On Linux and IRIX
systems, the pthread library is used. Under
Windows, critical sections are used.
by Perry R. Cook and Gary P. Scavone, 1995--2023.
*/
/***************************************************/
#include "Mutex.h"
namespace stk {
Mutex :: Mutex()
{
#if (defined(__OS_IRIX__) || defined(__OS_LINUX__) || defined(__OS_MACOSX__))
pthread_mutex_init(&mutex_, NULL);
pthread_cond_init(&condition_, NULL);
#elif defined(__OS_WINDOWS__)
InitializeCriticalSection(&mutex_);
condition_ = CreateEvent(NULL, // no security
true, // manual-reset
false, // non-signaled initially
NULL); // unnamed
#endif
}
Mutex :: ~Mutex()
{
#if (defined(__OS_IRIX__) || defined(__OS_LINUX__) || defined(__OS_MACOSX__))
pthread_mutex_destroy(&mutex_);
pthread_cond_destroy(&condition_);
#elif defined(__OS_WINDOWS__)
DeleteCriticalSection(&mutex_);
CloseHandle( condition_ );
#endif
}
void Mutex :: lock()
{
#if (defined(__OS_IRIX__) || defined(__OS_LINUX__) || defined(__OS_MACOSX__))
pthread_mutex_lock(&mutex_);
#elif defined(__OS_WINDOWS__)
EnterCriticalSection(&mutex_);
#endif
}
void Mutex :: unlock()
{
#if (defined(__OS_IRIX__) || defined(__OS_LINUX__) || defined(__OS_MACOSX__))
pthread_mutex_unlock(&mutex_);
#elif defined(__OS_WINDOWS__)
LeaveCriticalSection(&mutex_);
#endif
}
void Mutex :: wait()
{
#if (defined(__OS_IRIX__) || defined(__OS_LINUX__) || defined(__OS_MACOSX__))
pthread_cond_wait(&condition_, &mutex_);
#elif defined(__OS_WINDOWS__)
WaitForMultipleObjects(1, &condition_, false, INFINITE);
#endif
}
void Mutex :: signal()
{
#if (defined(__OS_IRIX__) || defined(__OS_LINUX__) || defined(__OS_MACOSX__))
pthread_cond_signal(&condition_);
#elif defined(__OS_WINDOWS__)
SetEvent( condition_ );
#endif
}
} // stk namespace