Implement a mutex using atomic compare-and-swap.
#include <stdatomic.h>
#include <sched.h>
typedef struct { atomic_int state; } cas_mutex_t; /* 0 = unlocked, 1 = locked */
#define CAS_MUTEX_INIT { 0 }
void cas_mutex_lock(cas_mutex_t *m)
{
int expected = 0;
while (!atomic_compare_exchange_weak_explicit(&m->state, &expected, 1,
memory_order_acquire, memory_order_relaxed)) {
expected = 0; /* CAS wrote the current value into expected: reset and retry */
sched_yield(); /* give the CPU away instead of spinning hard */
}
}
int cas_mutex_trylock(cas_mutex_t *m)
{
int expected = 0;
return atomic_compare_exchange_strong_explicit(&m->state, &expected, 1,
memory_order_acquire, memory_order_relaxed);
}
void cas_mutex_unlock(cas_mutex_t *m)
{
atomic_store_explicit(&m->state, 0, memory_order_release);
}
Points: CAS changes 0 → 1 only if the value is still 0, so exactly one thread wins; reset expected after a failed CAS. A real mutex sleeps instead of yielding in a loop: Linux uses a futex (state 0 = free, 1 = locked, 2 = locked with waiters; futex_wait/futex_wake only when contended), and RTOS mutexes put the task on a wait list. Real mutexes also record the owner (for priority inheritance and error checking). weak CAS may fail spuriously and belongs in loops; strong for single attempts.