KatInterview

Analyze Concurrency Hazards, Memory Coherence, and System Calls

System DesignModel answer
EasyModel answerSystem Designconcurrencyoperating-systemscaching

Last updated

Answer a three-part operating systems and concurrency question covering Coffman conditions, false sharing, spinlock hazards, and kernel-mode transitions.

In systems programming and kernel-adjacent software, small errors in synchronization logic, cache line layout, or kernel interface usage can cause severe performance degradation or deadlocks.

Address the following three scenarios:


Scenario 1: Deadlocks and Lock Inversion

Two threads execute functions that acquire two shared mutexes (mutex_a and mutex_b):

void process_left_to_right() {
    pthread_mutex_lock(&mutex_a);
    pthread_mutex_lock(&mutex_b);
    /* Work on A and B */
    pthread_mutex_unlock(&mutex_b);
    pthread_mutex_unlock(&mutex_a);
}

void process_right_to_left() {
    pthread_mutex_lock(&mutex_b);
    pthread_mutex_lock(&mutex_a);
    /* Work on B and A */
    pthread_mutex_unlock(&mutex_a);
    pthread_mutex_unlock(&mutex_b);
}
  1. Identify the four Coffman conditions required for a deadlock. Specify which condition is explicitly introduced by the control flow above.
  2. How can this deadlock risk be completely eliminated without altering the granularity of the locks? Provide C pseudocode demonstrating the solution for dynamically selected lock instances.

Scenario 2: Cache Coherence and Mutex vs. Spinlock

Two threads running on separate physical CPU cores update individual fields of a shared structure:

struct SystemCounters {
    uint64_t metric_core0; // updated exclusively by Core 0
    uint64_t metric_core1; // updated exclusively by Core 1
} counters;
  1. Explain the hardware-level mechanism causing severe throughput loss despite the absence of software lock contention or shared variable access.
  2. Show how to fix this issue in C or C++.
  3. Compare spinlock and mutex primitives. Describe a situation where a spinlock is appropriate, and detail the primary risks of using a spinlock on a single-core system or in a preemptible kernel context.

Scenario 3: Execution Modes and Hardware Exceptions

  1. Trace the low-level execution flow and hardware mechanics of a valid read() system call versus a memory access that raises a segmentation fault (SIGSEGV).
  2. Clearly distinguish between blocking, busy-waiting, and a hardware protection fault.

Hints

Hint 1

Recall the four Coffman conditions: Mutual Exclusion, Hold and Wait, No Preemption, and Circular Wait.

Hint 2

Consider cache line boundaries (typically 64 bytes) and how MESI cache invalidation messages behave when two cores modify adjacent memory addresses.

Hint 3

Differentiate between an intentional trap instruction (e.g., `syscall`) and an unintentional hardware exception (page fault or general protection fault).