</>EmbeddedInterview

Implement a spinlock.

Medium"Coding: Concurrency Primitives"
#include <stdatomic.h>

typedef struct { atomic_flag locked; } spinlock_t;
#define SPINLOCK_INIT { ATOMIC_FLAG_INIT }

static inline void spin_lock(spinlock_t *l)
{
    while (atomic_flag_test_and_set_explicit(&l->locked, memory_order_acquire)) {
        /* spin; add a CPU hint here: __asm__ volatile("yield") on Arm, or WFE with SEV on unlock */
    }
}

static inline void spin_unlock(spinlock_t *l)
{
    atomic_flag_clear_explicit(&l->locked, memory_order_release);
}

Points: acquire on lock and release on unlock keep the critical section's memory accesses inside it. Spin only for very short sections and only when the holder runs on another core; on a single core with pre-emption, the waiter just burns its time slice (kernels disable pre-emption while holding a spinlock, and use spin_lock_irqsave when an ISR can take the same lock). Improvements: test-and-test-and-set (spin on a plain load to reduce cache traffic), exponential back-off, ticket locks for fairness.