Skip to content

Instantly share code, notes, and snippets.

@jedisct1
Created October 13, 2011 22:22
Show Gist options
  • Save jedisct1/1285723 to your computer and use it in GitHub Desktop.
Save jedisct1/1285723 to your computer and use it in GitHub Desktop.
My trivial userland spinlock implementation
#ifndef SPINLOCKS_H
#define SPINLOCKS_H
#include <unistd.h>
typedef volatile char spinlock_t;
#if defined(__x86_64__) || defined(__i386) || defined(_X86_)
# define CPU_PAUSE __asm__ ("pause")
#else
# define CPU_PAUSE (void) 0
#endif
#define SPINLOCK_LOCK(L) \
do { \
if (__sync_lock_test_and_set((L), 1) != 0) { \
unsigned int spin_count = 0U; \
for (;;) { \
CPU_PAUSE; \
if (*(L) == 0U && \
__sync_lock_test_and_set((L), 1) == 0) { \
break; \
} \
if (++spin_count > 100U) { \
usleep(0); \
} \
} \
} \
ANNOTATE_WRITERLOCK_ACQUIRED((const void *) (L)); \
} while(0)
#define SPINLOCK_UNLOCK(L) \
do { \
__sync_lock_release(L); \
ANNOTATE_WRITERLOCK_RELEASED((const void *) (L)); \
} while(0)
#ifdef VALGRIND_INSTRUMENTATION
# include <valgrind/drd.h>
#endif
#ifndef ANNOTATE_WRITERLOCK_ACQUIRED
# define ANNOTATE_WRITERLOCK_ACQUIRED(A) (void) 0
# define ANNOTATE_WRITERLOCK_RELEASED(A) (void) 0
# define ANNOTATE_RWLOCK_CREATE(A) (void) 0
#endif
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment