16 #include "objfw-defs.h"
22 #if !defined(OF_HAVE_THREADS) || \
23 (!defined(OF_HAVE_PTHREADS) && !defined(OF_WINDOWS) && !defined(OF_AMIGAOS))
24 # error No mutexes available!
29 #if defined(OF_HAVE_PTHREADS)
31 typedef pthread_mutex_t OFPlainMutex;
32 #elif defined(OF_WINDOWS)
34 typedef CRITICAL_SECTION OFPlainMutex;
35 #elif defined(OF_AMIGAOS)
36 # include <exec/semaphores.h>
37 typedef struct SignalSemaphore OFPlainMutex;
40 #if defined(OF_HAVE_ATOMIC_OPS)
42 typedef volatile int OFSpinlock;
43 #elif defined(OF_HAVE_PTHREAD_SPINLOCKS)
44 typedef pthread_spinlock_t OFSpinlock;
46 typedef OFPlainMutex OFSpinlock;
49 #ifdef OF_HAVE_SCHED_YIELD
53 #if defined(OF_HAVE_RECURSIVE_PTHREAD_MUTEXES) || defined(OF_WINDOWS) || \
55 # define OFPlainRecursiveMutex OFPlainMutex
61 } OFPlainRecursiveMutex;
67 extern int OFPlainMutexNew(OFPlainMutex *mutex);
68 extern int OFPlainMutexLock(OFPlainMutex *mutex);
69 extern int OFPlainMutexTryLock(OFPlainMutex *mutex);
70 extern int OFPlainMutexUnlock(OFPlainMutex *mutex);
71 extern int OFPlainMutexFree(OFPlainMutex *mutex);
72 extern int OFPlainRecursiveMutexNew(OFPlainRecursiveMutex *rmutex);
73 extern int OFPlainRecursiveMutexLock(OFPlainRecursiveMutex *rmutex);
74 extern int OFPlainRecursiveMutexTryLock(OFPlainRecursiveMutex *rmutex);
75 extern int OFPlainRecursiveMutexUnlock(OFPlainRecursiveMutex *rmutex);
76 extern int OFPlainRecursiveMutexFree(OFPlainRecursiveMutex *rmutex);
86 #if defined(OF_HAVE_SCHED_YIELD)
88 #elif defined(OF_WINDOWS)
94 OFSpinlockNew(OFSpinlock *spinlock)
96 #if defined(OF_HAVE_ATOMIC_OPS)
99 #elif defined(OF_HAVE_PTHREAD_SPINLOCKS)
100 return pthread_spin_init(spinlock, 0);
102 return OFPlainMutexNew(spinlock);
107 OFSpinlockTryLock(OFSpinlock *spinlock)
109 #if defined(OF_HAVE_ATOMIC_OPS)
110 if (OFAtomicIntCompareAndSwap(spinlock, 0, 1)) {
111 OFAcquireMemoryBarrier();
116 #elif defined(OF_HAVE_PTHREAD_SPINLOCKS)
117 return pthread_spin_trylock(spinlock);
119 return OFPlainMutexTryLock(spinlock);
124 OFSpinlockLock(OFSpinlock *spinlock)
126 #if defined(OF_HAVE_ATOMIC_OPS)
129 for (i = 0; i < 10; i++)
130 if (OFSpinlockTryLock(spinlock) == 0)
133 while (OFSpinlockTryLock(spinlock) == EBUSY)
137 #elif defined(OF_HAVE_PTHREAD_SPINLOCKS)
138 return pthread_spin_lock(spinlock);
140 return OFPlainMutexLock(spinlock);
145 OFSpinlockUnlock(OFSpinlock *spinlock)
147 #if defined(OF_HAVE_ATOMIC_OPS)
148 bool ret = OFAtomicIntCompareAndSwap(spinlock, 1, 0);
150 OFReleaseMemoryBarrier();
152 return (ret ? 0 : EINVAL);
153 #elif defined(OF_HAVE_PTHREAD_SPINLOCKS)
154 return pthread_spin_unlock(spinlock);
156 return OFPlainMutexUnlock(spinlock);
161 OFSpinlockFree(OFSpinlock *spinlock)
163 #if defined(OF_HAVE_ATOMIC_OPS)
165 #elif defined(OF_HAVE_PTHREAD_SPINLOCKS)
166 return pthread_spin_destroy(spinlock);
168 return OFPlainMutexFree(spinlock);