>_
EngineeringNotes
← Back to OS Internals
Chapter 08

Coordination & Synchronization

Managing concurrent execution and maintaining data consistency across shared resources.

01

Concurrency Definitions

Concurrency is the execution of multiple instruction sequences at the same time. In an operating system, this occurs when several processes or threads execute in parallel on multiple cores, or interleave their execution dynamically on a single CPU core.

Thread Characteristics

  • Single sequence stream within a process.
  • An independent path of execution in a process.
  • Lightweight process representing an execution unit.
  • Shares process memory, code, heap, and resource handles with sibling threads.

Thread Scheduling

Threads are scheduled for execution based on their priority and allocated CPU time slices.

⭐ Every thread has its own Thread Control Block (TCB) to manage its Program Counter (PC), CPU registers, and execution state.

02

Thread Context Switching

When the CPU switches attention from one thread to another, it saves the current thread's state and loads the next thread's state. Because threads share memory space, thread context switches are significantly faster than process context switches.

1. Fast SwitchingNo memory address space switching required.
2. Preserved CacheL1/L2 CPU cache lines remain valid for the shared address space.
3. CPU RegistersOnly PC, Stack Pointer, and CPU Registers are swapped out.

💡 Single CPU Performance: Will a single CPU core gain performance from multi-threading? No. The CPU overhead of context switching between two threads outweighs the benefits, resulting in a net-zero performance gain for pure CPU-bound tasks.

03

Process vs Thread Memory Layout

While separate processes have completely isolated memory address spaces, threads share the parent process's Heap, Global Data, and Source Code segments, but maintain independent stacks.

Process memory structure (Isolated)
Stack (User Space)
↓ Stack & Heap Grow ↑
Heap (Dynamic Data)
Data (Globals)
Text (Source Code)
Multi-threaded process (Shared space)
Stack A
Stack B
Shared Heap
Shared Data
Shared Text