1
0
Fork 0
mirror of https://github.com/Atmosphere-NX/Atmosphere.git synced 2024-11-23 12:22:08 +00:00
Atmosphere/stratosphere/libstratosphere/include/stratosphere/hossynch.hpp
Léo Lam 5b3e8e1c5d stratosphere: Use RAII for locks
This renames the Mutex class member functions so that the mutex types
satisfy Lockable.

This makes them usable with standard std::scoped_lock
and std::unique_lock, which lets us use RAII and avoids the need
for a custom RAII wrapper :)
2018-07-10 09:38:18 -07:00

120 lines
2.4 KiB
C++

#pragma once
#include <switch.h>
class HosMutex {
private:
Mutex m;
public:
HosMutex() {
mutexInit(&this->m);
}
void lock() {
mutexLock(&this->m);
}
void unlock() {
mutexUnlock(&this->m);
}
bool try_lock() {
return mutexTryLock(&this->m);
}
};
class HosRecursiveMutex {
private:
RMutex m;
public:
HosRecursiveMutex() {
rmutexInit(&this->m);
}
void lock() {
rmutexLock(&this->m);
}
void unlock() {
rmutexUnlock(&this->m);
}
bool try_lock() {
return rmutexTryLock(&this->m);
}
};
class HosCondVar {
private:
CondVar cv;
Mutex m;
public:
HosCondVar() {
mutexInit(&m);
condvarInit(&cv, &m);
}
Result WaitTimeout(u64 timeout) {
return condvarWaitTimeout(&cv, timeout);
}
Result Wait() {
return condvarWait(&cv);
}
Result Wake(int num) {
return condvarWake(&cv, num);
}
Result WakeOne() {
return condvarWakeOne(&cv);
}
Result WakeAll() {
return condvarWakeAll(&cv);
}
};
class HosSemaphore {
private:
CondVar cv;
Mutex m;
u64 count;
public:
HosSemaphore() {
count = 0;
mutexInit(&m);
condvarInit(&cv, &m);
}
HosSemaphore(u64 c) : count(c) {
mutexInit(&m);
condvarInit(&cv, &m);
}
void Signal() {
mutexLock(&this->m);
count++;
condvarWakeOne(&cv);
mutexUnlock(&this->m);
}
void Wait() {
mutexLock(&this->m);
while (!count) {
condvarWait(&cv);
}
count--;
mutexUnlock(&this->m);
}
bool TryWait() {
mutexLock(&this->m);
bool success = false;
if (count) {
count--;
success = true;
}
mutexUnlock(&this->m);
return success;
}
};