Friday, April 20, 2018

using CAS to implyment spinlock

#define CAS __sync_bool_compare_and_swap
bool __sync_bool_compare_and_swap (type *ptr, type oldval type newval, ...)
type __sync_val_compare_and_swap (type *ptr, type oldval type newval, ...)
These builtins perform an atomic compare and swap. That is, if the current value of *ptr is oldval, then write newval into *ptr.The “bool” version returns true if the comparison is successful and newval was written. The “val” version returns the contents of *ptr before the operation. 

static inline void my_spinlock(unsigned int *lock){
    while (!CAS(lock, 0, 1));
}
static inline void my_spinunlock(unsigned int *lock) {
    *lock = 0;
    //CAS(lock, 1, 0);
}

No comments:

Post a Comment