Operating Systems

Threads

A schedulable execution context. Threads in one process share an address space.

Level: intermediate

What is it?

A thread is an independently schedulable flow of execution with its own registers, program counter, stack, and thread-local state. Threads belonging to the same process normally share code, heap, and open process resources, while separate processes typically have separate virtual address spaces.

Why does it matter?

Threads can improve responsiveness and throughput when work can overlap, but shared memory introduces races and synchronization costs. A bug in one thread can corrupt shared process state used by all other threads.

Mental model

One process is a workshop; threads are workers sharing the tools and materials. Each worker has a separate current task and stack, but they must coordinate when touching the same mutable object.

How it works

  • Threads in one process share the address space but do not share each other's register state or ordinary stacks.
  • Concurrency means operations overlap in time; parallelism means multiple operations execute simultaneously on different cores.
  • Threads can block independently on I/O, locks, timers, and other wait conditions.
  • Synchronization establishes ordering or mutual exclusion around shared invariants.
  • More threads do not guarantee faster execution; contention, memory bandwidth, and scheduling overhead can dominate.

Steps

  • Two threads increment a shared counter.
  • Each reads the counter's old value before either write is complete.
  • Both compute the same next value and one update is lost without synchronization.
  • Use a mutex, atomic operation, or message-passing design appropriate to the invariant.

Real-world usage

  • Running independent I/O tasks concurrently.
  • Keeping a user interface responsive while background work proceeds.
  • Implementing bounded worker pools for request or job processing.

Common mistakes

  • Saying every thread has a separate process address space.
  • Assuming code with no explicit locks is thread-safe because the test passed once.
  • Creating unbounded threads without considering memory, scheduling, and downstream capacity.

Interview questions

Which resources are commonly shared by threads in one process?

Code, heap, global variables, and process resources such as file descriptors are commonly shared; stacks and register state are per-thread.

When would multiple processes be preferable to threads?

When stronger fault or security isolation is worth the extra communication and memory-management cost, or when components have different privilege boundaries.

How would you protect a shared counter?

Use a mutex around the read-modify-write operation or an atomic increment if that operation matches the required semantics.

Prerequisites

Related concepts

Continue learning

Browse the full computer science library