-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimpleMutex.h
More file actions
99 lines (83 loc) · 2.06 KB
/
SimpleMutex.h
File metadata and controls
99 lines (83 loc) · 2.06 KB
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
#ifndef __SIMPLE_MUTEX_H
#define __SIMPLE_MUTEX_H
#ifdef _XBOX360
#include "Console1Includes.h"
#elif defined(_WIN32)
#include <windows.h>
#else
#include <pthread.h>
#include <sys/types.h>
#endif
#include <assert.h>
/// \brief An easy to use mutex.
///
/// I wrote this because the version that comes with Windows is too complicated and requires too much code to use.
/// @remark Previously I used this everywhere, and in fact for a year or two HexNet was totally threadsafe. While doing profiling, I saw that this function was incredibly slow compared to the blazing performance of everything else, so switched to single producer / consumer everywhere. Now the user thread of HexNet is not threadsafe, but it's 100X faster than before.
class SimpleMutex
{
public:
/// Constructor
inline SimpleMutex();
// Destructor
virtual inline ~SimpleMutex();
// Locks the mutex. Slow!
inline void Lock(void);
// Unlocks the mutex.
inline void Unlock(void);
private:
#ifdef _WIN32
CRITICAL_SECTION criticalSection; /// Docs say this is faster than a mutex for single process access
#else
pthread_mutex_t hMutex;
#endif
};
// ---------------------------- inline functions -------------------------------------
SimpleMutex::SimpleMutex()
{
#ifdef _WIN32
// hMutex = CreateMutex(NULL, FALSE, 0);
// assert(hMutex);
InitializeCriticalSection(&criticalSection);
#else
int error = pthread_mutex_init(&hMutex, 0);
(void) error;
assert(error==0);
#endif
}
SimpleMutex::~SimpleMutex()
{
#ifdef _WIN32
// CloseHandle(hMutex);
DeleteCriticalSection(&criticalSection);
#else
pthread_mutex_destroy(&hMutex);
#endif
}
#ifdef _WIN32
#ifdef _DEBUG
#include <stdio.h>
#endif
#endif
void SimpleMutex::Lock(void)
{
#ifdef _WIN32
if (&criticalSection)
EnterCriticalSection(&criticalSection);
#else
int error = pthread_mutex_lock(&hMutex);
(void) error;
assert(error==0);
#endif
}
void SimpleMutex::Unlock(void)
{
#ifdef _WIN32
// ReleaseMutex(hMutex);
LeaveCriticalSection(&criticalSection);
#else
int error = pthread_mutex_unlock(&hMutex);
(void) error;
assert(error==0);
#endif
}
#endif