Simulant
21.12-1319
A portable game engine for Windows, OSX, Linux, Dreamcast, and PSP
simulant
threads
mutex.h
1
#pragma once
2
3
#include <stdexcept>
4
5
#ifdef __PSP__
6
#include <pspthreadman.h>
7
#elif defined(__DREAMCAST__)
8
#include <kos/thread.h>
9
#include <kos/mutex.h>
10
#elif defined(_MSC_VER)
11
#include <stdbool.h>
12
#include <windows.h>
13
#else
14
#include "pthread.h"
15
#endif
16
17
namespace
smlt
{
18
namespace
thread {
19
20
#if defined(_MSC_VER)
21
typedef
CRITICAL_SECTION pthread_mutex_t;
22
typedef
void
pthread_mutexattr_t;
23
typedef
HANDLE pthread_t;
24
typedef
CONDITION_VARIABLE pthread_cond_t;
25
#endif
26
27
class
MutexInitialisationError
:
28
public
std::runtime_error {
29
30
public
:
31
MutexInitialisationError
():
32
std::runtime_error(
"Mutex initialisation failed"
) {}
33
};
34
35
class
Mutex
{
36
public
:
37
friend
class
Condition
;
38
39
Mutex
();
40
~
Mutex
();
41
42
Mutex
(
const
Mutex
&) =
delete
;
43
44
bool
try_lock();
45
void
lock();
46
void
unlock();
47
48
private
:
49
#ifdef __PSP__
50
SceUID semaphore_;
51
uint32_t owner_ = 0;
52
#elif defined(__DREAMCAST__)
53
mutex_t mutex_;
54
#else
55
pthread_mutex_t mutex_;
56
#endif
57
};
58
59
class
RecursiveMutex
{
60
public
:
61
friend
class
Condition
;
62
63
RecursiveMutex
();
64
~
RecursiveMutex
();
65
66
RecursiveMutex
(
const
RecursiveMutex
&) =
delete
;
67
68
void
lock();
69
void
unlock();
70
private
:
71
#ifdef __PSP__
72
SceUID semaphore_;
73
uint32_t owner_ = 0;
74
int32_t recursive_ = 0;
75
#elif defined(__DREAMCAST__)
76
mutex_t mutex_;
77
#else
78
pthread_mutex_t mutex_;
79
#endif
80
};
81
82
template
<
typename
M>
83
class
Lock
{
84
public
:
85
explicit
Lock
(M& m):
86
mutex_(m) {
87
88
mutex_.lock();
89
}
90
91
~
Lock
() {
92
mutex_.unlock();
93
}
94
95
private
:
96
M& mutex_;
97
};
98
99
template
<
typename
M>
100
class
ToggleLock
;
101
102
template
<>
103
class
ToggleLock
<
Mutex
> {
104
public
:
105
explicit
ToggleLock
(
Mutex
& m):
106
mutex_(m) {
107
mutex_.lock();
108
}
109
110
~
ToggleLock
() {
111
mutex_.unlock();
112
}
113
114
void
lock() {
115
mutex_.lock();
116
}
117
118
void
unlock() {
119
mutex_.unlock();
120
}
121
122
private
:
123
Mutex
& mutex_;
124
};
125
126
}
127
}
smlt
Definition:
animation.cpp:25
smlt::thread::Condition
Definition:
condition.h:8
smlt::thread::Lock
Definition:
mutex.h:83
smlt::thread::MutexInitialisationError
Definition:
mutex.h:28
smlt::thread::RecursiveMutex
Definition:
mutex.h:59
smlt::thread::ToggleLock
Definition:
mutex.h:100
smlt::thread::Mutex
Definition:
mutex.h:35
Generated by
1.8.20