jorrit.schaap Posted October 29, 2014 Posted October 29, 2014 Hi, running my program in valgrind (callgrind) I noticed a lot of CPU cycles are spent doing noting in spinlock and waitlock. Looking at the code below this is no surprise, since the while loops are spinning full speed. *******BEGIN ORIGINAL SOURCE**************** INLINE void SpinLock(volatile int *ptr,int old_value,int new_value) { #ifdef _CELLOS_LV2 while(!AtomicCAS(ptr,old_value,new_value)) { sys_timer_usleep(1); } #else while(!AtomicCAS(ptr,old_value,new_value)) { } #endif}INLINE void WaitLock(volatile int *ptr,int value) { #ifdef _CELLOS_LV2 while(!AtomicCAS(ptr,value,value)) { sys_timer_usleep(1); } #else while(!AtomicCAS(ptr,value,value)) { } #endif} *******END ORIGINAL SOURCE**************** Here is my proposal for an improved version which is also platform independent. *******BEGIN IMPROVED SOURCE**************** INLINE void SpinLock(volatile int *ptr,int old_value,int new_value) { while(!AtomicCAS(ptr,old_value,new_value)) { Timer::usleep(1); } INLINE void WaitLock(volatile int *ptr,int value) { while(!AtomicCAS(ptr,value,value)) { Timer::usleep(1); } } *******END IMPROVED SOURCE****************
ulf.schroeter Posted October 31, 2014 Posted October 31, 2014 Spinlocks are much more efficient for short-term thread blocking as they avoid context switching (which would be forced by usleep ()). Even though your CPU load is higher, overall performance with this approach is better. http://en.m.wikipedia.org/wiki/Spinlock
Recommended Posts