Advertisement
WeltEnSTurm

Untitled

Sep 11th, 2012
431
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.46 KB | None | 0 0
  1.  
  2. #include "ws/base.hpp"
  3. #include "ws/exception.hpp"
  4. #include "ws/sys/mutex.hpp"
  5.  
  6. namespace ws {
  7.     namespace sys {
  8.  
  9. #if defined(SYSTEM_WINDOWS)
  10.  
  11.         Mutex::Mutex(): locked(false){
  12.             mutexHandle = CreateMutex(NULL, FALSE, NULL);
  13.             if(!mutexHandle)
  14.                 throw Exception("failed to retrieve mutex");
  15.         }
  16.  
  17.         void Mutex::lock(){
  18.             switch(WaitForSingleObject(mutexHandle, 2000)){
  19.                 case WAIT_TIMEOUT:
  20.                     throw Exception("mutex did not get lock in time (2 seconds maximum)");
  21.                 case WAIT_ABANDONED:
  22.                     throw Exception("mutex owner thread quit without unlocking.");
  23.                 case WAIT_FAILED:
  24.                     throw Exception("mutex failed with error " + GetLastError());
  25.             }
  26.             locked = true;
  27.         }
  28.  
  29.         void Mutex::unlock(){
  30.             locked = false;
  31.             ReleaseMutex(mutexHandle);
  32.         }
  33.  
  34. #elif defined(SYSTEM_LINUX)
  35.  
  36.         Mutex::Mutex(): locked(false){
  37.             mutexHandle = PTHREAD_MUTEX_INITIALIZER;
  38.             if(pthread_mutex_init(&mutexHandle, 0) == -1)
  39.                 throw Exception("mutex creation failed");
  40.  
  41.         }
  42.  
  43.         void Mutex::lock(){
  44.             if(pthread_mutex_lock(&mutexHandle) == -1)
  45.                 throw Exception("failed to lock");
  46.         }
  47.  
  48.         void Mutex::unlock(){
  49.             if(pthread_mutex_unlock(&mutexHandle) == -1)
  50.                 throw Exception("failed to unlock");
  51.         }
  52.  
  53. #endif
  54.  
  55.         scopeLock::scopeLock(Mutex& m){
  56.             mutex = &m;
  57.             mutex->lock();
  58.         }
  59.  
  60.         scopeLock::~scopeLock(){
  61.             if(mutex->locked)
  62.                 mutex->unlock();
  63.         }
  64.  
  65.         void scopeLock::unlock(){
  66.             if(mutex->locked)
  67.                 mutex->unlock();
  68.         }
  69.     }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement