Advertisement
Guest User

Untitled

a guest
Mar 20th, 2012
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.18 KB | None | 0 0
  1.  
  2. #if defined OS_WINDOWS
  3. struct Lock //thanks to 'doublep' from StackOverflow for this RAII solution
  4. {
  5.   MUTEX&  mutex;
  6.   bool    locked;
  7.  
  8.   Lock (MUTEX& mutex)
  9.     : mutex (mutex),
  10.       locked (false)
  11.   { }
  12.  
  13.   ~Lock ()
  14.   { release (); }
  15.  
  16.   bool acquire (int timeout = -1)
  17.   {
  18.     if (!locked && WaitForSingleObject (mutex, timeout) == WAIT_OBJECT_0)
  19.       locked = true;
  20.     return locked;
  21.   }
  22.  
  23.   int release ()
  24.   {
  25.     if (locked)
  26.       locked = (ReleaseMutex (mutex) == 1);
  27.     return !locked;
  28.   }
  29. };
  30.  
  31. MUTEX mutex_q = NULL;
  32. MUTEX mutex_p = NULL;
  33. #else
  34. struct Lock //and here is my little edit for linux
  35. {
  36.   MUTEX&  mutex;
  37.   bool    locked;
  38.  
  39.   Lock (MUTEX& mutex)
  40.     : mutex (mutex),
  41.       locked (false)
  42.   { }
  43.  
  44.   ~Lock ()
  45.   { release (); }
  46.  
  47.   bool acquire (int timeout = -1)
  48.   {
  49.     if (!locked && pthread_mutex_lock (&mutex) == 0)
  50.       locked = true;
  51.     return locked;
  52.   }
  53.  
  54.   int release ()
  55.   {
  56.     if (locked)
  57.       locked = (pthread_mutex_unlock (&mutex) == 1);
  58.     return !locked;
  59.   }
  60. };
  61.  
  62. MUTEX mutex_q = PTHREAD_MUTEX_INITIALIZER;
  63. MUTEX mutex_p = PTHREAD_MUTEX_INITIALIZER;
  64.  
  65. #endif
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement