Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
executable file 139 lines (99 sloc) 2.25 KB
#ifndef com_sleepless_sys_mutex_cpp
#define com_sleepless_sys_mutex_cpp
/* Copyright 2004 Sleepless Software Inc. All Rights Reserved */
#ifdef WIN32
#include <windows.h>
#endif
#if defined(linux) || (defined(__APPLE__) && defined(__GNUC__)) || __CYGWIN__
#include <pthread.h>
#include <errno.h>
#endif
struct Mutex
{
#ifdef WIN32
HANDLE mutex;
Mutex(const char *name)
{
mutex = CreateMutex(0, 0, name);
// This can really return NULL in practice
}
Mutex()
{
mutex = CreateMutex(0, 0, 0);
// could, theoretically return NULL, but I doubt that's ever
// going to happen.
}
~Mutex()
{
CloseHandle(mutex);
}
void lock()
{
WaitForSingleObject(mutex, INFINITE);
}
void unlock()
{
ReleaseMutex(mutex);
}
// Tries for 'millis' milliseconds to obtain the lock on the mutex.
// Returns 0 if calling thread managed to get the lock, or 1 if the
// lock could not be obtained before the time expired.
int tryLock(int millis = 0)
{
DWORD s = WaitForSingleObject(mutex, millis);
return (s == WAIT_TIMEOUT) ? 1 : 0;
}
#endif
#if defined(linux) || (defined(__APPLE__) && defined(__GNUC__)) || __CYGWIN__
pthread_mutex_t mutex;
Mutex()
{
pthread_mutex_init(&mutex, NULL);
}
~Mutex()
{
}
void lock()
{
//tryLock(); // XXX why was was i calling this? makes no sense.
pthread_mutex_lock(&mutex); // XXX this can return a deadlock prevention error
}
void unlock()
{
pthread_mutex_unlock(&mutex);
}
// Returns 1 if the mutex is already locked by somone else, or
// 0 if calling thread got a lock on the mutex.
int tryLock()
{
return (pthread_mutex_trylock(&mutex) == EBUSY) ? 1 : 0;
}
#endif
#ifdef __palmos__
// Not sure palm os has the concept of threads, which makes a mutex
// sort of irrelevant. Right.
// I actually put the methods in here though, because other lib
// code depends on this struct. The fact that the calls are here,
// but empty, results in things like Queue.cpp work as though
// they were simply non-thread-safe.
Mutex()
{
}
~Mutex()
{
}
void lock()
{
}
void unlock()
{
}
// Returns 1 if the mutex is already locked by somone else, or
// 0 if calling thread got a lock on the mutex.
int tryLock()
{
return 0;
}
#endif
};
#endif // com_sleepless_sys_mutex_cpp