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)
31typedef pthread_mutex_t OFPlainMutex;
32#elif defined(OF_WINDOWS)
34typedef CRITICAL_SECTION OFPlainMutex;
35#elif defined(OF_AMIGAOS)
36# include <exec/semaphores.h>
37typedef struct SignalSemaphore OFPlainMutex;
40#if defined(OF_HAVE_ATOMIC_OPS)
42typedef volatile int OFSpinlock;
43#elif defined(OF_HAVE_PTHREAD_SPINLOCKS)
44typedef pthread_spinlock_t OFSpinlock;
46typedef 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;
67extern int OFPlainMutexNew(OFPlainMutex *mutex);
68extern int OFPlainMutexLock(OFPlainMutex *mutex);
69extern int OFPlainMutexTryLock(OFPlainMutex *mutex);
70extern int OFPlainMutexUnlock(OFPlainMutex *mutex);
71extern int OFPlainMutexFree(OFPlainMutex *mutex);
72extern int OFPlainRecursiveMutexNew(OFPlainRecursiveMutex *rmutex);
73extern int OFPlainRecursiveMutexLock(OFPlainRecursiveMutex *rmutex);
74extern int OFPlainRecursiveMutexTryLock(OFPlainRecursiveMutex *rmutex);
75extern int OFPlainRecursiveMutexUnlock(OFPlainRecursiveMutex *rmutex);
76extern int OFPlainRecursiveMutexFree(OFPlainRecursiveMutex *rmutex);
86#if defined(OF_HAVE_SCHED_YIELD)
88#elif defined(OF_WINDOWS)
94OFSpinlockNew(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);
107OFSpinlockTryLock(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);
124OFSpinlockLock(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);
145OFSpinlockUnlock(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);
161OFSpinlockFree(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);