c - How does Compare and Swap work? -
i have read quite posts compare , swap guarantees atomicity, still not able how it??this general pseudo code compare , swap -
int cas(int *ptr,int oldvalue,int newvalue) { int temp = *ptr; if(*ptr == oldvalue) *ptr = newvalue return temp; } how guarantee atomicity. example, if using implement mutex,
void lock(int *mutex) { while(!cas(mutex, 0 , 1)); } how prevent 2 threads acquiring mutex @ same time? pointers appreciated.
"general pseudo code" not actual code of cas (compare , swap) implementation. special hardware instructions used activate special atomic hardware in cpu. example, in x86 lock cmpxchg can used (http://en.wikipedia.org/wiki/compare-and-swap).
in gcc, example, there __sync_val_compare_and_swap() builtin - implements hardware-specific atomic cas. there description of operation fresh wonderful book paul e. mckenney (is parallel programming hard, and, if so, can it?, 2014), section 4.3 "atomic operations", pages 31-32.
if want know more building higher level synchronization on top of atomic operations , save system spinlocks , burning cpu cycles on active spinning, can read futex mechanism in linux. first paper on futexes futexes tricky ulrich drepper 2011; other lwn article http://lwn.net/articles/360699/ (and historic 1 fuss, futexes , furwocks: fast userland locking in linux, 2002)
mutex locks described ulrich use atomic operations "fast path" (when mutex not locked , our thread wants lock it), if mutex locked, thread go sleeping using futex(futex_wait...) (and mark mutex variable using atomic operation, inform unlocking thread "there sleeping waiting on mutex", unlocker know must wake them using futex(futex_wake, ...)
Comments
Post a Comment