I'm using a spin lock to protect a very small critical section. Contention happens very rarely so a spin lock is more appropriate than a regular mutex.
My current code is as follows, and assumes x86 and GCC:
volatile int exclusion = 0;
void lock() {
while (__sync_lock_test_and_set(&exclusion, 1)) {
// Do nothing. This GCC builtin instruction
// ensures memory barrier.
}
}
void unlock() {
__sync_synchronize(); // Memory barrier.
exclusion = 0;
}
So I'm wondering:
__sync_lock_release
. I'm not an expert on memory barriers so I'm not sure whether it's okay for me to use this instead of __sync_synchronize
.I do not care at all about contention. There may be 1, maybe 2 other threads trying to lock the spin lock once every few days.