1 /* 2 * Copyright 2010, Lucian Adrian Grijincu, lucian.grijincu@gmail.com. 3 * Distributed under the terms of the MIT License. 4 */ 5 6 7 #include <pthread.h> 8 9 #include <arch_cpu_defs.h> 10 11 #include "pthread_private.h" 12 13 14 #define UNLOCKED 0 15 #define LOCKED 1 16 17 18 int 19 pthread_spin_init(pthread_spinlock_t* lock, int pshared) 20 { 21 // This implementation of spinlocks doesn't differentiate 22 // between spin locks used by threads in the same process or 23 // between threads of different processes. 24 25 lock->lock = UNLOCKED; 26 return 0; 27 } 28 29 30 int 31 pthread_spin_destroy(pthread_spinlock_t* lock) 32 { 33 return 0; 34 } 35 36 37 int 38 pthread_spin_lock(pthread_spinlock_t* lock) 39 { 40 while (atomic_test_and_set((int32*)&lock->lock, LOCKED, UNLOCKED) 41 == LOCKED) { 42 SPINLOCK_PAUSE(); // spin 43 // TODO: On UP machines we should thread_yield() in the loop. 44 } 45 return 0; 46 } 47 48 49 int 50 pthread_spin_trylock(pthread_spinlock_t* lock) 51 { 52 if (atomic_test_and_set((int32*)&lock->lock, LOCKED, UNLOCKED) == LOCKED) 53 return EBUSY; 54 return 0; 55 } 56 57 58 int 59 pthread_spin_unlock(pthread_spinlock_t* lock) 60 { 61 lock->lock = UNLOCKED; 62 return 0; 63 } 64