1 // https://idea.popcount.org/2012-09-12-reinventing-spinlocks/ 2 // See https://stackoverflow.com/questions/8177031/does-mac-os-x-have-pthread-spinlock-t-type 3 4 #include <errno.h> 5 #include <sched.h> 6 7 #ifndef PTHREAD_SPIN_LOCK_SHIM 8 #define PTHREAD_SPIN_LOCK_SHIM 9 10 typedef int pthread_spinlock_t; 11 12 #ifndef PTHREAD_PROCESS_SHARED 13 # define PTHREAD_PROCESS_SHARED 1 14 #endif 15 #ifndef PTHREAD_PROCESS_PRIVATE 16 # define PTHREAD_PROCESS_PRIVATE 2 17 #endif 18 pthread_spin_init(pthread_spinlock_t * lock,int pshared)19static inline int pthread_spin_init(pthread_spinlock_t *lock, int pshared) { 20 __asm__ __volatile__("" ::: "memory"); 21 *lock = 0; 22 return 0; 23 } 24 pthread_spin_destroy(pthread_spinlock_t * lock)25static inline int pthread_spin_destroy(pthread_spinlock_t *lock) { 26 return 0; 27 } 28 pthread_spin_lock(pthread_spinlock_t * lock)29static inline int pthread_spin_lock(pthread_spinlock_t *lock) { 30 while (1) { 31 int i; 32 for (i = 0; i < 10000; i++) { 33 if (__sync_bool_compare_and_swap(lock, 0, 1)) { 34 return 0; 35 } 36 } 37 sched_yield(); 38 } 39 } 40 pthread_spin_trylock(pthread_spinlock_t * lock)41static inline int pthread_spin_trylock(pthread_spinlock_t *lock) { 42 if (__sync_bool_compare_and_swap(lock, 0, 1)) { 43 return 0; 44 } 45 return EBUSY; 46 } 47 pthread_spin_unlock(pthread_spinlock_t * lock)48static inline int pthread_spin_unlock(pthread_spinlock_t *lock) { 49 __asm__ __volatile__("" ::: "memory"); 50 *lock = 0; 51 return 0; 52 } 53 #endif 54