KatInterview

Concurrency Models: Processes, Threads, and Shared Memory Safety

BehavioralModel answer
MediumModel answerBehavioralconcurrencyoperating-systemsmultithreading

Last updated

Contrast processes and threads in terms of isolation and resource sharing, then explain synchronization challenges in multithreaded programs.

Concurrency Models: Processes, Threads, and Shared Memory Safety

Operating systems provide different abstractions for concurrent execution. Understanding these models and their trade-offs is essential for building correct, efficient software.

Part 1: Architectural Differences

Compare and contrast processes versus threads along these dimensions:

  • How memory address spaces are organized and isolated
  • Ownership of system resources like file handles and network connections
  • The computational cost of creating new execution units and switching between them

Part 2: Shared Memory Challenges

When multiple threads execute within the same process, they can directly read and write the same memory locations. Identify two distinct categories of bugs that emerge from this shared-memory model, explaining the underlying mechanism that causes each problem.

Part 3: Correctness Strategies

Describe practical approaches developers use to prevent these concurrency bugs. Include specific synchronization mechanisms and explain when each is appropriate.

Concrete Scenario

Consider a shared variable total = 0 accessed by two threads that each execute total = total + 1 one time. Walk through why the final value might be 1 instead of the expected 2, and explain what guarantees are needed to ensure correctness.

Hints

Hint 1

Think about what happens at the assembly or bytecode level when incrementing a variable—it's not a single instruction

Hint 2

Memory operations can be reordered by compilers and CPUs, and cores cache values independently

Hint 3

Different synchronization tools have different performance characteristics and semantic guarantees