Deadlocks, Cache-Line False Sharing, Spinlocks, and Kernel Traps

Easy · Software Engineering Fundamentals · System Software Engineer · Technical Screen

Prompt

Kernel, storage, and networking software depends on predictable thread synchronization, cache-aware memory layouts, and hardware privilege isolation. Analyze the three systems engineering cases below.

Case 1 — Lock Ordering and Deadlock

Two concurrent worker threads move records between two shared shards guarded by mtx_a and mtx_b:

void migrate_a_to_b(void) {
    pthread_mutex_lock(&mtx_a);
    pthread_mutex_lock(&mtx_b);
    /* move entries from shard A to shard B */
    pthread_mutex_unlock(&mtx_b);
    pthread_mutex_unlock(&mtx_a);
}

void migrate_b_to_a(void) {
    pthread_mutex_lock(&mtx_b);
    pthread_mutex_lock(&mtx_a);
    /* move entries from shard B to shard A */
    pthread_mutex_unlock(&mtx_a);
    pthread_mutex_unlock(&mtx_b);
}
  1. List the four Coffman conditions required for a deadlock, and clarify whether those conditions are satisfied or broken here—naming the specific condition introduced by the reversed acquisition sequence.
  2. Show the standard locking discipline that eliminates this deadlock while keeping fine-grained per-shard locks (mtx_a and mtx_b) rather than merging them into a single coarse lock.

Case 2 — CPU Cache Lines and Synchronization Primitives

Two worker threads pinned to separate physical CPU cores continually increment their own 64-bit packet counters inside a shared struct:

struct CoreMetrics {
    uint64_t rx_core0; /* updated exclusively on Core 0 */
    uint64_t rx_core1; /* updated exclusively on Core 1 */
} metrics;
  1. Explain why throughput drops sharply in tight loops even though each thread touches a distinct struct member with zero locks.
  2. Show how to fix this bottleneck in C or C++.
  3. Explain when a spinlock (pthread_spin_lock) is preferable to a sleeping mutex (pthread_mutex_lock), and describe the failure or throughput hazards a spinlock creates on a uniprocessor machine or under thread/vCPU preemption.

Case 3 — Kernel Privilege Transitions and Faults

  1. Walk through and contrast the CPU and OS kernel steps when a user-space thread executes a valid read() system call versus when it dereferences an unmapped pointer that triggers SIGSEGV.
  2. Distinguish sleeping/blocking (pthread_mutex_lock), busy-waiting (pthread_spin_lock), and a hardware protection fault across CPU utilization, scheduler thread state, and kernel involvement.

Scope & Expectations

  • Trace the exact interleavings and hardware mechanisms behind lock cycles, 64-byte MESI cache-line invalidations, and Ring 3 to Ring 0 transitions.
  • Provide concrete C/C++ fixes for static/dynamic lock ordering (preserving per-shard locks) and cache-line separation (alignas / local batching).
  • Clearly separate voluntary waiting strategies (sleeping in the kernel vs. user-space atomic polling) from involuntary CPU exceptions raised by the MMU.

Step-by-step walkthrough

  1. Case 1.1: Deadlock interleaving and the four Coffman conditions

    A deadlock is a permanent freeze in which each thread in a group is blocked waiting for a resource held by another thread in the same group, so none of them can ever proceed.

    In Case 1, migrate_a_to_b acquires mtx_a then mtx_b, whereas migrate_b_to_a acquires mtx_b then mtx_a. Most runs succeed by luck, which makes this bug treacherous in testing, but under concurrent load the scheduler can interleave the two threads like this:

    Time   Thread 1 (migrate_a_to_b: A -> B)     Thread 2 (migrate_b_to_a: B -> A)
    ----   -----------------------------------   -----------------------------------
     t1    pthread_mutex_lock(&mtx_a) [OK]
     t2                                          pthread_mutex_lock(&mtx_b) [OK]
     t3    pthread_mutex_lock(&mtx_b) [BLOCKS]   (waiting on mtx_b, held by Thread 2)
     t4                                          pthread_mutex_lock(&mtx_a) [BLOCKS]
                                                 (waiting on mtx_a, held by Thread 1)
    
    Wait-for graph:  Thread 1 ---> Thread 2 ---> Thread 1   (cycle => deadlock!)
    

    A deadlock can happen if and only if all four Coffman conditions hold at the same time:

    1. Mutual exclusion: Only one thread can hold a given resource (mtx_a or mtx_b) at a time.
    2. Hold and wait: A thread already holding at least one lock (mtx_a) continues holding it while waiting to acquire another (mtx_b).
    3. No preemption: A lock cannot be forcibly yanked away from its holder by another thread; only the holder can call pthread_mutex_unlock.
    4. Circular wait: A closed chain of threads exists (Thread 1 -> Thread 2 -> Thread 1) in which each thread waits for a lock held by the next thread in the chain.

    Satisfied vs. broken: None of the four Coffman conditions is broken—all four are simultaneously satisfied, and Circular wait is the specific condition introduced by acquiring (mtx_a, mtx_b) in reversed sequences (breaking a consistent lock-ordering rule).

  2. Case 1.2: Preventing circular wait with a global lock order

    Lock granularity measures how small a slice of data each lock protects. Replacing mtx_a and mtx_b with a single coarse global mutex would stop the deadlock, but it would serialize completely unrelated shard operations and break the requirement to keep fine-grained per-shard locks.

    The standard pattern is a global lock hierarchy (total lock ordering): assign a strict rank to every lock in the system and require every code path to acquire locks in strictly increasing rank order (release order does not affect deadlock, though unlocking in reverse LIFO order is clean practice).

    Why a global order makes cycles impossible: Suppose a cycle T1 -> T2 -> ... -> Tk -> T1 formed while holding locks L1, L2, ..., Lk. Because every thread only waits for a lock ranked strictly higher than the lock it already holds, we would have rank(L1) < rank(L2) < ... < rank(Lk) < rank(L1)—a mathematical contradiction (rank(L1) < rank(L1)).

    Fixing Case 1 requires changing only the acquisition sequence inside migrate_b_to_a so both routines lock mtx_a before mtx_b:

    void migrate_b_to_a(void) {
        pthread_mutex_lock(&mtx_a);   /* Global rank 1: always acquire mtx_a first */
        pthread_mutex_lock(&mtx_b);   /* Global rank 2: always acquire mtx_b second */
        /* move entries from shard B to shard A */
        pthread_mutex_unlock(&mtx_b);
        pthread_mutex_unlock(&mtx_a);
    }
    

    When two locks are chosen dynamically at runtime (such as migrate(shard_u, shard_v)), sort the two pointers by unique shard ID—or by integer memory address via uintptr_t (avoiding undefined relational < comparisons on unrelated pointers in ISO C)—and guard against a == b so a thread never locks the same non-recursive mutex twice:

    #include <pthread.h>
    #include <stdint.h>
    
    void lock_both_ordered(pthread_mutex_t *a, pthread_mutex_t *b) {
        if (a == b) {
            pthread_mutex_lock(a);     /* Self-move: lock once, not twice! */
            return;
        }
        if ((uintptr_t)a > (uintptr_t)b) {
            pthread_mutex_t *tmp = a;
            a = b;
            b = tmp;
        }
        pthread_mutex_lock(a);         /* Always lower address first */
        pthread_mutex_lock(b);
    }
    

    (In modern C++17, std::scoped_lock lock(mtx_a, mtx_b); automatically acquires multiple mutexes using a deadlock-avoidance algorithm regardless of argument order.)

  3. Case 2.1: Why adjacent per-core counters suffer false sharing

    Even though Core 0 writes only metrics.rx_core0 (8 bytes) and Core 1 writes only metrics.rx_core1 (8 bytes), both fields sit side by side inside one 16-byte struct. CPU caches do not track individual bytes or 8-byte integers; they move and track memory in fixed-size aligned blocks called cache lines—64 bytes on standard x86-64 and most server ARM CPUs (128 bytes on Apple M-series CPUs).

    Single 64-byte CPU cache line (bytes 0 .. 63):
    +----------------+----------------+----------------------------------------+
    | rx_core0 (8B)  | rx_core1 (8B)  |       unused / neighboring vars (48B)  |
    +----------------+----------------+----------------------------------------+
      Core 0 writes ^  Core 1 writes ^       --> BOTH map to the SAME cache line!
    

    Multi-core CPUs keep caches consistent using a cache-coherence protocol such as MESI (Modified, Exclusive, Shared, Invalid), which enforces a single-writer rule per cache line: before Core 0 can modify any byte in a cache line, it must acquire exclusive ownership (Read-For-Ownership) and invalidate that entire 64-byte line in Core 1's cache.

    Step   Core 0                             Core 1
    ----   --------------------------------   --------------------------------
     1     rx_core0++ -> claims line (M)      Core 1's copy marked Invalid (I)
     2     Core 0's copy marked Invalid (I)   rx_core1++ -> steals line (M)
     3     rx_core0++ -> steals line (M)      Core 1's copy marked Invalid (I)
    

    This invisible hardware tug-of-war over unrelated variables in the same cache line is false sharing. An L1 cache hit takes roughly ~1 ns, whereas bouncing a dirty cache line between physical cores over the interconnect typically costs ~40–100 ns (even more across CPU sockets), degrading tight counter loops by an order of magnitude without a single lock in sight.

  4. Case 2.2: Eliminating false sharing in C and C++

    There are two complementary fixes: separate the counters onto distinct cache lines in memory, or stop writing shared memory on every single packet.

    Fix 1 — Align each hot field to its own 64-byte cache line (alignas): In C11 (<stdalign.h>) and C++11/17, alignas(64) forces both the start of the struct and the second field onto separate 64-byte boundaries (inserting 56 bytes of compiler padding after each 8-byte counter, growing sizeof(struct CoreMetrics) from 16 bytes to 128 bytes):

    #include <stdalign.h>
    #include <stdint.h>
    
    #define CACHE_LINE_BYTES 64
    
    struct CoreMetrics {
        alignas(CACHE_LINE_BYTES) uint64_t rx_core0; /* Bytes 0..63   (Cache line 0) */
        alignas(CACHE_LINE_BYTES) uint64_t rx_core1; /* Bytes 64..127 (Cache line 1) */
    };
    

    In C++17, you can also use std::hardware_destructive_interference_size (typically 64 or 128, accounting for adjacent-line spatial prefetchers on some CPUs) and std::atomic<uint64_t> with std::memory_order_relaxed so a background reporting thread can read the counters without a C++ data race.

    Fix 2 — Accumulate in a register or thread-local variable and flush in batches (even faster): Keep a plain local uint64_t local_rx = 0; in a CPU register during hot packet processing and add it into metrics only once every K (e.g., 1,024) packets—turning 100,000,000 cross-core memory updates into fewer than 100,000 L1-free flushes.

  5. Case 2.3: Spinlock vs. mutex, single-core hazards, and holder preemption

    • Mutex (pthread_mutex_lock): If the lock is already taken, the thread asks the OS kernel (via futex on Linux) to put it to sleep, freeing the CPU core to run other threads until unlock wakes it. A contended sleep-and-wake round trip takes roughly 2–10 microseconds (2,000–10,000 ns).
    • Spinlock (pthread_spin_lock): If the lock is taken, the thread stays awake on its CPU core in a tight user-space atomic loop (while (lock_is_taken) cpu_pause();), acquiring the lock within tens of nanoseconds the instant it is released.

    When to prefer a spinlock over a mutex: 1. The critical section is extremely short (tens to a few hundred nanoseconds—much shorter than two ~3 us context switches) and never blocks (no I/O, no sleeping allocator, no page faults). 2. The system has multiple physical cores, the lock holder is actively running on another core, and runnable threads do not exceed available cores. 3. Or in OS kernel interrupt context (or when scheduler preemption is disabled), where sleeping is illegal because an interrupt handler has no schedulable thread context to put to sleep.

    Hardware and scheduler risks of spinlocks: - On a single-core CPU: Only one thread can execute at any instant. If Thread B spins waiting for a lock held by Thread A, Thread A cannot run on the single core to release the lock! Under preemptive time-sharing, Thread B burns 100% CPU for its entire multi-millisecond scheduler quantum accomplishing nothing; under cooperative scheduling, kernel code with preemption disabled, or real-time SCHED_FIFO priorities (where high-priority B refuses to yield to low-priority A), the machine hangs permanently. - Under preemption on multicore / virtualized systems (lock-holder preemption): If the OS scheduler—or a cloud hypervisor pausing a virtual CPU—preempts the lock holder mid-critical-section, every waiting thread spins at 100% CPU for milliseconds waiting on a sleeping thread, collapsing system-wide throughput.

  6. Case 3.1: CPU and kernel steps for read() vs. SIGSEGV

    Modern CPUs enforce isolation using hardware privilege levels (on x86-64: unprivileged Ring 3 for user applications and privileged Ring 0 for the OS kernel; on ARM64: EL0 and EL1) together with the MMU (Memory Management Unit), the hardware circuit that translates virtual addresses into physical RAM addresses and checks read/write/execute permissions on every memory instruction.

    Both read() and dereferencing a bad pointer trigger a synchronous transition from Ring 3 to Ring 0 (caused directly by the currently executing instruction rather than an external hardware timer/NIC interrupt), but their hardware triggers, saved instruction pointers, and outcomes are fundamentally different:

    Stage                Valid read(fd, buf, n) syscall         Invalid pointer (*p = 1, p = NULL)
    -------------------  -------------------------------------  -------------------------------------
    1. Trigger           Intentional programmatic TRAP:         Unintentional hardware FAULT:
                         libc puts SYS_read in RAX and runs     CPU executes ordinary MOV; MMU walks
                         the `syscall` instruction (svc on ARM) page tables, finds 0x0 unmapped
    2. Ring 3 -> Ring 0  CPU switches to Ring 0 via fast MSR    CPU raises Page Fault (#PF, IDT #14),
       & saved PC        entry; saves NEXT instruction address  stores bad address in CR2, switches to
                         (RIP after `syscall`)                  Ring 0, saves FAULTING instruction RIP
    3. Kernel work       Switches to kernel stack; validates    Page-fault handler inspects process
                         fd & user buffer; if data isn't ready, Virtual Memory Areas (VMAs); sees 0x0
                         BLOCKS thread until disk/socket ready; is outside any valid mapped region
                         copies data via copy_to_user()
    4. Return / outcome  Returns (`sysret`) to NEXT user        Queues SIGSEGV (si_addr = 0x0); on
                         instruction with bytes read in RAX     return path, invokes signal handler or
                                                                terminates process (core dump)
    

    Notice why the saved instruction pointer (RIP) differs: a system call is a finished request, so it must resume after syscall; a page fault is potentially repairable (for example, loading a swapped-out page from disk), so saving the faulting instruction lets the CPU seamlessly retry that exact MOV when a fault is valid—whereas for an unmapped NULL write, the kernel aborts the thread with SIGSEGV. (Bonus nuance: passing buf = NULL as an argument to read(fd, NULL, 64) does not raise SIGSEGV in user space—the kernel catches the bad destination inside copy_to_user and cleanly returns -1 with errno = EFAULT.)

  7. Case 3.2: Blocking vs. busy-waiting vs. a hardware protection fault

    Dimension           Blocking                  Busy-waiting               Hardware protection fault
                        (pthread_mutex_lock)      (pthread_spin_lock)        (invalid memory / priv op)
    ------------------  ------------------------  -------------------------  --------------------------
    Category            Voluntary synchronization Voluntary synchronization  Involuntary CPU exception
                        (sleep-based waiting)     (poll-based waiting)       (isolation enforcement)
    Thread state        Removed from run queue    Remains Runnable/Running   Traps into kernel fault
                        (Blocked / Sleeping)      in a tight user-space loop handler immediately
    CPU core usage      0% while waiting; core    100% of one core spinning  Not a wait loop; executes
                        runs other threads        on atomic cache checks     kernel exception handler
    OS kernel involved? Yes, on contention        No (pure user-space atomic Always (hardware vectors
                        (futex wait / futex wake) instructions)              straight into Ring 0)
    How it resolves     Lock owner unlocks and    Lock owner clears word;    Kernel maps valid page and
                        kernel reschedules thread next atomic check succeeds retries instruction, OR
                        (~2-10 microseconds)      (~tens of nanoseconds)     delivers SIGSEGV / SIGBUS
    

    In short: - Blocking trades a microsecond-scale kernel context switch to save CPU cores whenever a wait might not be immediate. - Busy-waiting burns CPU cycles intentionally to avoid scheduler latency across tiny multi-core critical sections. - A hardware protection fault is not a synchronization or waiting strategy at all—it is the CPU's MMU or privilege-check hardware catching an illegal memory access or privileged instruction in Ring 3 and handing control to the Ring 0 kernel to repair or terminate the process.

Intuition & how it works

Picture a shared workshop to build an instant mental model for all three low-level systems cases: - Deadlock and lock ordering: Two carpenters both need a hammer (mtx_a) and a saw (mtx_b). If Carpenter 1 grabs the hammer first and waits for the saw while Carpenter 2 grabs the saw first and waits for the hammer, both stand frozen forever. Numbering every tool on the wall (#1 hammer, #2 saw) and requiring everyone to pick up lower-numbered tools first guarantees that one carpenter gets both tools, finishes, and hands them over. - False sharing: Even if two coworkers write on separate columns of the same clipboard (rx_core0 and rx_core1), only one person can hold the physical clipboard at a time—which is exactly how CPU cores fight over a 64-byte cache line (the fixed-size chunk of memory CPU caches transfer and lock as a unit). Giving each coworker their own clipboard (alignas(64)) stops the tug-of-war. - System calls vs. faults, and sleeping vs. spinning: Calling read() is walking up to a service window and politely handing over a request slip (an intentional trap into the OS kernel), whereas dereferencing an unmapped pointer is trying to walk through a locked staff-only door so a security alarm summons the kernel (SIGSEGV). Meanwhile, blocking is taking a pager buzz-number and sitting down so others can use the counter, whereas busy-waiting (spinning) is standing at the window asking "Ready yet?" a billion times per second.

Naive assumptions fail badly in concurrent systems programming. Assuming "reversed lock orders passed unit tests, so they are safe" misses rare thread interleavings that freeze production servers days later; assuming "separate struct fields mean zero contention" misses 64-byte hardware cache lines; and assuming "spinlocks beat mutexes because they avoid the kernel" turns into catastrophic CPU burn or a permanent hang on a uniprocessor machine or under scheduler preemption.

Walk through two tiny traces to see the fixes work: 1. Lock hierarchy on 2 shard locks (mtx_a rank 1, mtx_b rank 2): Thread 1 calls lock(mtx_a) and succeeds. Thread 2 also calls lock(mtx_a) first—instead of grabbing mtx_b—so Thread 2 sleeps cleanly at step 1 while Thread 1 acquires mtx_b, moves the shard entries, and unlocks both, waking Thread 2 with zero cycle. 2. Cache-line alignment on 2 uint64_t packet counters: Without alignment, rx_core0 (bytes 0..7) and rx_core1 (bytes 8..15) sit in cache line 0 (0..63), bouncing across cores at ~50 ns per increment; with alignas(64), rx_core0 lives at byte 0 (line 0) and rx_core1 lives at byte 64 (line 1), so both cores increment independently in their own L1 caches at ~1 ns per packet.

Key points

  • All four Coffman conditions must hold simultaneously for a deadlock: Mutual exclusion, Hold and wait, No preemption, and Circular wait. Reversed lock sequences (mtx_a -> mtx_b vs. mtx_b -> mtx_a) create Circular wait; enforcing a global lock order (by static rank, shard ID, or uintptr_t address, guarding a == b) eliminates cycles while preserving fine-grained per-shard locks.
  • False sharing is hardware contention without logical sharing: Under MESI (the CPU cache-coherence protocol that grants only one core exclusive write ownership of a 64-byte cache line at a time), two adjacent 8-byte counters written by separate cores continually invalidate each other's L1 cache line. Fix it with alignas(64) per field—or accumulate in a register/thread-local counter and flush in batches.
  • Spinlock vs. mutex trade-offs: Use a spinlock only when critical sections take tens to a few hundred nanoseconds (far below a ~2–10 us kernel futex sleep/wake cycle), the holder is actively running on another physical core, and runnable threads do not outnumber cores—or inside kernel interrupt handlers that cannot sleep. On a single core or when the lock holder gets preempted, spinning starves the very thread needed to release the lock.
  • read() system call vs. SIGSEGV invalid dereference: Both synchronously switch the CPU from unprivileged Ring 3 (user mode) to privileged Ring 0 (kernel mode). syscall is an intentional trap that saves the next instruction address, optionally blocks for I/O, and returns a byte count or -errno; an unmapped pointer triggers an MMU (Memory Management Unit) page fault (#PF) that saves the faulting instruction address, checks the process's Virtual Memory Areas (VMAs), and delivers SIGSEGV when the address is unmapped or forbidden.
  • Blocking vs. busy-waiting vs. protection fault: Blocking yields the CPU in the kernel until woken (0% CPU while waiting); busy-waiting polls atomically in a tight loop (100% of one core); a hardware protection fault is not a wait primitive at all, but an involuntary CPU exception enforcing memory or privilege isolation.

Common mistakes

  • Getting tripped up on whether a Coffman condition is "broken": Deadlock happens when all four conditions are satisfied simultaneously; what the buggy code breaks is global lock ordering, which makes Circular wait hold.
  • Replacing mtx_a and mtx_b with a single global mutex: That stops the deadlock only by destroying concurrency across unrelated shards, violating the fine-grained locking requirement.
  • Forgetting if (a == b) when sorting dynamic lock pairs: Calling pthread_mutex_lock twice on the same default (non-recursive) mutex deadlocks a single thread against itself.
  • Adding padding bytes only at the end of a struct without alignas(64): If metrics starts at byte 48 of a cache line, two 8-byte fields at offsets 48 and 56 still share a cache line or bleed into neighboring variables; always align and pad.
  • Saying every system call performs a full thread context switch: Entering the kernel via syscall is a fast mode switch on the same thread; a full scheduler switch to a different thread only happens if read() blocks waiting for data or the time slice expires.
  • Assuming every page fault crashes the program: Most page faults in healthy programs are valid lazy allocations (demand paging) or copy-on-write pages that the kernel resolves transparently without raising SIGSEGV.

Follow-up questions

  • How can Thread-Local Storage (thread_local / _Thread_local) eliminate both mutex contention and cache-line bouncing in hot-path telemetry? Thread-Local Storage (thread_local in C++, _Thread_local in C11) gives each thread its own private counter or ring buffer inside that thread's separate TLS memory segment. On the hot path, each thread updates only its own variable with zero locks, zero atomic instructions, and zero shared cache lines. Periodically (for example, every 4,096 packets or once per second) or on thread exit, each thread flushes its batch into a global atomic aggregator—turning 80,000,000 contended cross-core updates across 8 threads into fewer than 20,000 batched updates.
  • What causes priority inversion when threads of different scheduling priorities share a mutex, and how does priority inheritance fix it? Priority inversion happens when a high-priority thread H blocks waiting for a mutex held by a low-priority thread L, and an unrelated medium-priority CPU-bound thread M preempts L—indirectly forcing H to wait behind M for an unbounded duration (famously causing watchdog resets on NASA's 1997 Mars Pathfinder). With priority inheritance (PTHREAD_PRIO_INHERIT), as soon as H blocks on L's mutex, the OS scheduler temporarily raises L's effective priority to H's level so M cannot preempt L; once L unlocks the mutex, L reverts to its normal priority and H runs immediately.
  • When a user instruction triggers a hardware page fault, how does the kernel distinguish a valid demand-paged address from an illegal access that sends SIGSEGV? When malloc or mmap reserves virtual memory, the kernel initially records only a Virtual Memory Area (VMA) range without wiring physical RAM frames. On first touch, the MMU raises a #PF exception into Ring 0, saving the faulting instruction's address (RIP) and placing the accessed virtual address in CR2 (on x86-64). If the address falls inside a valid VMA with matching read/write/execute flags, the kernel allocates a zeroed 4 KiB physical frame (a minor fault, or loads file/swap data on a major fault), updates the page table, and returns to Ring 3 to retry the exact faulting instruction transparently; if no VMA covers the address or permissions conflict, the kernel delivers SIGSEGV.

Follow-up questions

Similar questions

More Netapp interview questions

All 9 Netapp questions →