I'm trying to create a custom mutex class based on the Allegro mutex (cross-platform). I am not using C++11. I'm trying to do it like this, but it seems to be a bit superfluous:
template <class T>
class Mutex
{
private:
ALLEGRO_MUTEX *mutex = NULL;
ALLEGRO_THREAD *owner = NULL;
T *data = NULL;
public:
Mutex ();
Mutex (T* data);
~Mutex ();
bool lock (ALLEGRO_THREAD* thread);
bool unlock (ALLEGRO_THREAD* thread);
bool trylock (); //Returns true if you can lock the thread
bool set (T* data, ALLEGRO_THREAD* thread);
bool get (T** data, ALLEGRO_THREAD* thread); //Pass reference of pointer
}
The constructors will call al_create_mutex()
and, in the case of the second one, set the data pointer. The destructor calls al_destroy_mutex()
.
The lock method will check to see if owner
is NULL
(indicating the mutex is unlocked and no thread owns it). If it is NULL
, then it will set owner = thread
and lock the mutex. The unlock method unlocks the mutex if thread == owner
and sets owner = NULL
.
The trylock method simply checks to see if owner == NULL
, indicating that the mutex is not locked by any thread.
The set
and get
methods will set and return the stored pointer, only if the calling thread is the owner of the locked mutex.
I have a feeling that i'm going a bit overboard with the whole passing the thread every time you want to call a method, but i don't see any other way to make this class thread-safe, since Allegro doesn't have a al_get_current_thread()
function or something like that. What should i do with this class?