Simulant  21.12-574
A portable game engine for Windows, OSX, Linux, Dreamcast, and PSP
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 #else
11 #include "pthread.h"
12 #endif
13 
14 namespace smlt {
15 namespace thread {
16 
18  public std::runtime_error {
19 
20 public:
22  std::runtime_error("Mutex initialisation failed") {}
23 };
24 
25 class Mutex {
26 public:
27  friend class Condition;
28 
29  Mutex();
30  ~Mutex();
31 
32  Mutex(const Mutex&) = delete;
33 
34  bool try_lock();
35  void lock();
36  void unlock();
37 
38 private:
39 #ifdef __PSP__
40  SceUID semaphore_;
41  uint32_t owner_ = 0;
42 #elif defined(__DREAMCAST__)
43  mutex_t mutex_;
44 #else
45  pthread_mutex_t mutex_;
46 #endif
47 };
48 
50 public:
51  friend class Condition;
52 
54  ~RecursiveMutex();
55 
56  RecursiveMutex(const RecursiveMutex&) = delete;
57 
58  void lock();
59  void unlock();
60 private:
61 #ifdef __PSP__
62  SceUID semaphore_;
63  uint32_t owner_ = 0;
64  int32_t recursive_ = 0;
65 #elif defined(__DREAMCAST__)
66  mutex_t mutex_;
67 #else
68  pthread_mutex_t mutex_;
69 #endif
70 };
71 
72 template<typename M>
73 class Lock {
74 public:
75  explicit Lock(M& m):
76  mutex_(m) {
77 
78  mutex_.lock();
79  }
80 
81  ~Lock() {
82  mutex_.unlock();
83  }
84 
85 private:
86  M& mutex_;
87 };
88 
89 template<typename M>
90 class ToggleLock;
91 
92 template<>
93 class ToggleLock<Mutex> {
94 public:
95  explicit ToggleLock(Mutex& m):
96  mutex_(m) {
97  mutex_.lock();
98  }
99 
100  ~ToggleLock() {
101  mutex_.unlock();
102  }
103 
104  void lock() {
105  mutex_.lock();
106  }
107 
108  void unlock() {
109  mutex_.unlock();
110  }
111 
112 private:
113  Mutex& mutex_;
114 };
115 
116 }
117 }
smlt
Definition: animation.cpp:25
smlt::thread::Condition
Definition: condition.h:8
smlt::thread::Lock
Definition: mutex.h:73
smlt::thread::MutexInitialisationError
Definition: mutex.h:18
smlt::thread::RecursiveMutex
Definition: mutex.h:49
smlt::thread::ToggleLock
Definition: mutex.h:90
smlt::thread::Mutex
Definition: mutex.h:25