Explications à venir |
#include "Mutex.h"
#include <windows.h>
struct Mutex::Impl {
virtual void obtenir() const volatile = 0;
virtual void relacher() const volatile = 0;
virtual ~Impl() = default;
};
struct ImplUsager : Mutex::Impl {
mutable CRITICAL_SECTION cs;
ImplUsager() {
InitializeCriticalSection(&cs);
}
~ImplUsager() {
DeleteCriticalSection(&cs);
}
void obtenir() const volatile override {
EnterCriticalSection(&const_cast<ImplUsager*>(this)->cs);
}
void relacher() const volatile override {
LeaveCriticalSection(&const_cast<ImplUsager*>(this)->cs);
}
};
struct ImplSysteme : Mutex::Impl {
void obtenir() const volatile override {
WaitForSingleObject(h, INFINITE);
}
void relacher() const volatile override {
ReleaseMutex(h);
}
HANDLE h;
ImplSysteme() : h{ CreateMutex(0, FALSE, 0) } {
}
~ImplSysteme() {
CloseHandle(h);
}
};
Mutex::Mutex() : Mutex{ Usager{} } {
}
Mutex::Mutex(Systeme) : p{ new ImplSysteme } {
}
Mutex::Mutex(Usager) : p{ new ImplUsager } {
}
Mutex::~Mutex() = default;
void Mutex::obtenir() const volatile {
const_cast<unique_ptr<Impl>&>(p)->obtenir();
}
void Mutex::relacher() const volatile {
const_cast<unique_ptr<Impl>&>(p)->relacher();
}
|