Skip to content

Instantly share code, notes, and snippets.

@candeira
Last active August 29, 2015 14:14
Show Gist options
  • Save candeira/99cb7e8da35809b50765 to your computer and use it in GitHub Desktop.
Save candeira/99cb7e8da35809b50765 to your computer and use it in GitHub Desktop.
Attempting to macro-ize gallir's spinlock
// macro-ize gallir's spinlock code from:
// http://stackoverflow.com/questions/6704252/atomic-memcpy-suggestion/28286503#28286503
// third version, thanks to kragen for explains of expression/statement and do/while protective coding
#define SPINLOCK(lock) do { while ((lock) || ! __sync_bool_compare_and_swap(&(lock) , 0 , 1));} while (0)
#define SPINUNLOCK(lock) (lock) = 0;
// and the wrap-a-block version
#define SPINLOCKME(lock, statement_or_block) \
do { \
lock_p * _mylock = &(lock); \
while (*_mylock) || ! __sync_bool_compare_and_swap(_mylock , 0 , 1)); \
statement_or_block; \
*_mylock = 0; \
} while(0)
// for reference, my second attempt:
#define SPINLOCK(lock) while (lock || ! __sync_bool_compare_and_swap(&lock , 0 , 1));
#define SPINUNLOCK(lock) lock = 0;
//
// for reference, my first attempt: will probably not work because of whitespace in code, but first attempt at a macro ever.
#define SPINLOCKME(lock, code) { \
while (lock || ! __sync_bool_compare_and_swap(&lock , 0 , 1)); \
code; \
lock = 0; \
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment