radare2/libr/util/lock.c

72 lines
1.5 KiB
C
Raw Normal View History

/* radare - LGPL - Copyright 2009-2013 - pancake */
#include <r_th.h>
/* locks/mutex/sems */
2010-06-27 22:14:06 +02:00
R_API struct r_th_lock_t *r_th_lock_new() {
RThreadLock *thl = R_NEW(RThreadLock);
if (thl) {
thl->refs = 0;
#if HAVE_PTHREAD
pthread_mutex_init (&thl->lock, NULL);
#elif __WIN32__
//thl->lock = CreateSemaphore(NULL, 0, 1, NULL);
InitializeCriticalSection(&thl->lock);
#endif
}
return thl;
}
2010-06-27 22:14:06 +02:00
R_API int r_th_lock_wait(struct r_th_lock_t *thl) {
#if HAVE_PTHREAD
2010-06-27 22:14:06 +02:00
r_th_lock_enter (thl);
r_th_lock_enter (thl); // locks here
r_th_lock_leave (thl); // releases previous mutex
#elif __WIN32__
2010-03-25 10:18:59 +01:00
WaitForSingleObject (thl->lock, INFINITE);
#else
2010-06-27 22:14:06 +02:00
while (r_th_lock_check ());
#endif
return 0;
}
2010-06-27 22:14:06 +02:00
R_API int r_th_lock_enter(struct r_th_lock_t *thl) {
#if HAVE_PTHREAD
pthread_mutex_lock(&thl->lock);
#elif __WIN32__
EnterCriticalSection(&thl->lock);
#endif
return ++thl->refs;
}
2010-06-27 22:14:06 +02:00
R_API int r_th_lock_leave(struct r_th_lock_t *thl) {
#if HAVE_PTHREAD
pthread_mutex_unlock(&thl->lock);
#elif __WIN32__
LeaveCriticalSection(&thl->lock);
//ReleaseSemaphore (thl->lock, 1, NULL);
#endif
if (thl->refs>0)
thl->refs--;
return thl->refs;
}
2010-06-27 22:14:06 +02:00
R_API int r_th_lock_check(struct r_th_lock_t *thl) {
//w32 // TryEnterCriticalSection(&thl->lock);
return thl->refs;
}
2010-06-27 22:14:06 +02:00
R_API void *r_th_lock_free(struct r_th_lock_t *thl) {
if (thl) {
#if HAVE_PTHREAD
2010-06-27 22:14:06 +02:00
pthread_mutex_destroy (&thl->lock);
#elif __WIN32__
2010-06-27 22:14:06 +02:00
DeleteCriticalSection (&thl->lock);
CloseHandle (thl->lock);
#endif
free(thl);
}
return NULL;
}