11 #include <drift/dslcore.h>
15 #include <drift/Mutex.h>
16 #include <drift/Threading.h>
19 DSL_Mutex_pthreads::DSL_Mutex_pthreads(
int timeout) {
21 lock_timeout = timeout;
22 memset(&hMutex, 0,
sizeof(hMutex));
25 pthread_mutexattr_t pma;
26 memset(&pma, 0,
sizeof(pma));
27 pthread_mutexattr_init(&pma);
28 pthread_mutexattr_settype(&pma, PTHREAD_MUTEX_RECURSIVE);
29 pthread_mutex_init(&hMutex, &pma);
30 pthread_mutexattr_destroy(&pma);
33 DSL_Mutex_pthreads::~DSL_Mutex_pthreads() {
34 pthread_mutex_destroy(&hMutex);
37 bool DSL_Mutex_pthreads::Lock() {
38 if (lock_timeout >= 0) {
39 return Lock(lock_timeout);
42 int n = pthread_mutex_lock(&hMutex);
44 printf(
"Error locking mutex! (%p, %p, %d, %s)\n",
this, &hMutex, n, strerror(n));
47 LockingThreadID = pthread_self();
49 if (refcnt <= 0) { refcnt = 1; }
53 bool DSL_Mutex_pthreads::Lock(
int timeo) {
54 int64 timeout = timeo;
55 struct timespec abs_time;
56 memset(&abs_time, 0,
sizeof(abs_time));
57 if (clock_gettime(CLOCK_REALTIME, &abs_time) == 0) {
58 abs_time.tv_sec += (timeout / 1000);
59 timeout -= (timeout / 1000);
60 abs_time.tv_nsec += timeout * 1000000;
61 while (abs_time.tv_nsec >= 1000000000LL) {
63 abs_time.tv_nsec -= 1000000000LL;
65 if (abs_time.tv_nsec < 0) {
66 printf(
"Timed mutex lock nsec < 0! (%p, %p, %llu, %llu)\n",
this, &hMutex, abs_time.tv_sec, abs_time.tv_nsec);
69 int n = pthread_mutex_timedlock(&hMutex, &abs_time);
72 printf(
"Error locking mutex! (%p, %p, %d, %s)\n",
this, &hMutex, n, strerror(n));
73 printf(
"" I64FMT
" / " I64FMT
"\n", abs_time.tv_sec, abs_time.tv_nsec);
80 int amIn = pthread_mutex_trylock(&hMutex);
83 safe_sleep(100,
true);
85 amIn = pthread_mutex_trylock(&hMutex);
88 printf(
"Error locking mutex! (%p, %p, %s)\n",
this, &hMutex, strerror(errno));
95 LockingThreadID = GetCurrentThreadId();
97 if (refcnt <= 0) { refcnt = 1; }
101 void DSL_Mutex_pthreads::Release() {
106 int n = pthread_mutex_unlock(&hMutex);
108 printf(
"Error unlocking mutex! (%p, %p, %d, %s)\n",
this, &hMutex, n, strerror(n));
113 THREADIDTYPE DSL_Mutex_pthreads::LockingThread() {
114 return LockingThreadID;
117 bool DSL_Mutex_pthreads::IsLockMine() {
118 if (refcnt > 0 && pthread_equal(pthread_self(), LockingThreadID)) {
return true; }
122 bool DSL_Mutex_pthreads::IsLocked() {
123 if (refcnt > 0) {
return true; }