Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "ws/base.hpp"
- #include "ws/exception.hpp"
- #include "ws/sys/mutex.hpp"
- namespace ws {
- namespace sys {
- #if defined(SYSTEM_WINDOWS)
- Mutex::Mutex(): locked(false){
- mutexHandle = CreateMutex(NULL, FALSE, NULL);
- if(!mutexHandle)
- throw Exception("failed to retrieve mutex");
- }
- void Mutex::lock(){
- switch(WaitForSingleObject(mutexHandle, 2000)){
- case WAIT_TIMEOUT:
- throw Exception("mutex did not get lock in time (2 seconds maximum)");
- case WAIT_ABANDONED:
- throw Exception("mutex owner thread quit without unlocking.");
- case WAIT_FAILED:
- throw Exception("mutex failed with error " + GetLastError());
- }
- locked = true;
- }
- void Mutex::unlock(){
- locked = false;
- ReleaseMutex(mutexHandle);
- }
- #elif defined(SYSTEM_LINUX)
- Mutex::Mutex(): locked(false){
- mutexHandle = PTHREAD_MUTEX_INITIALIZER;
- if(pthread_mutex_init(&mutexHandle, 0) == -1)
- throw Exception("mutex creation failed");
- }
- void Mutex::lock(){
- if(pthread_mutex_lock(&mutexHandle) == -1)
- throw Exception("failed to lock");
- }
- void Mutex::unlock(){
- if(pthread_mutex_unlock(&mutexHandle) == -1)
- throw Exception("failed to unlock");
- }
- #endif
- scopeLock::scopeLock(Mutex& m){
- mutex = &m;
- mutex->lock();
- }
- scopeLock::~scopeLock(){
- if(mutex->locked)
- mutex->unlock();
- }
- void scopeLock::unlock(){
- if(mutex->locked)
- mutex->unlock();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement