Spinlock: Difference between revisions

Jump to navigation Jump to search
[unchecked revision][unchecked revision]
Content deleted Content added
m →‎External Links: Added another external link
Sebastian (talk | contribs)
m →‎C Macros: Avoid using legacy ‘__sync’ builtins
Line 114: Line 114:
Here are example macros in C you can use for spinlocks:
Here are example macros in C you can use for spinlocks:
<source lang="c">
<source lang="c">
#define DECLARE_LOCK(name) volatile int name ## Locked
#define DECLARE_LOCK(name) volatile int name
#define LOCK(name) \
#define LOCK(name) \
while (!__sync_bool_compare_and_swap(& name ## Locked, 0, 1)); \
while (!__atomic_compare_exchange_n(&name, (void *)false, true, false, \
__ATOMIC_ACQ_REL, __ATOMIC_RELAXED)) \
__sync_synchronize();
while (name) \
#define UNLOCK(name) \
asm volatile("pause")
__sync_synchronize(); \
#define UNLOCK(name) __atomic_store_n(&name, false, __ATOMIC_RELEASE)
name ## Locked = 0;
</source>
</source>
Call DECLARE_LOCK(name) to create a lock definition, LOCK(name) to acquire the lock, and UNLOCK(name) to release it. The LOCK macro will spin until the lock is released before continuing. This code makes use of intrisics specific to GCC, but it also compiles on Clang.
Call DECLARE_LOCK(name) to create a lock definition, LOCK(name) to acquire the lock, and UNLOCK(name) to release it. The LOCK macro will spin until the lock is released before continuing. This code makes use of intrisics specific to GCC, but it also compiles on Clang.