Created
December 12, 2013 16:30
-
-
Save nbergont/7930868 to your computer and use it in GitHub Desktop.
Just a mutex class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef TinyMutex_h | |
#define TinyMutex_h | |
#if defined(_WIN32) || defined(__WIN32__) | |
#define WIN32_LEAN_AND_MEAN | |
#include <windows.h> | |
#include <process.h> | |
#elif defined(__GNUC__) | |
#include <pthread.h> | |
#endif | |
class TinyMutex | |
{ | |
public: | |
TinyMutex() | |
{ | |
#if defined(_WIN32) || defined(__WIN32__) | |
_mutex = CreateMutex(0, FALSE, 0); | |
#elif defined(__GNUC__) | |
pthread_mutex_init(&_mutex, NULL); | |
#endif | |
} | |
~TinyMutex() | |
{ | |
#if defined(_WIN32) || defined(__WIN32__) | |
CloseHandle(_mutex); | |
#elif defined(__GNUC__) | |
pthread_mutex_destroy(&_mutex); | |
#endif | |
} | |
bool lock() | |
{ | |
#if defined(_WIN32) || defined(__WIN32__) | |
return WaitForSingleObject(_mutex, INFINITE) != WAIT_FAILED; | |
#elif defined(__GNUC__) | |
return pthread_mutex_lock(&_mutex) == 0; | |
#endif | |
return false; | |
} | |
bool unlock() | |
{ | |
#if defined(_WIN32) || defined(__WIN32__) | |
return ReleaseMutex(_mutex) == TRUE; | |
#elif defined(__GNUC__) | |
return pthread_mutex_unlock(&_mutex) == 0; | |
#endif | |
return false; | |
} | |
private: | |
#if defined(_WIN32) || defined(__WIN32__) | |
HANDLE _mutex; | |
#elif defined(__GNUC__) | |
pthread_mutex_t _mutex; | |
#endif | |
}; | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment