Chapter 4: Threads

Threads vs. Processes

  • Process - Heavyweight unit of execution with its own memory space. - Context switching between processes is expensive. - Processes do not share memory by default.

  • Thread - Lightweight unit of execution within a process. - Shares code, data, and resources of the process. - Each thread has its own program counter, register set, and stack. - Cheaper and faster context switching than processes.

Benefits of Multithreading

  • Responsiveness: Applications remain interactive even during long tasks.

  • Resource Sharing: Threads share memory and resources of a process.

  • Economy: More efficient than creating new processes.

  • Scalability: Can take advantage of multiprocessor systems.

Multithreading Models

Many-to-One

  • Multiple user-level threads map to a single kernel thread.

  • If one thread blocks, the entire process blocks.

User Threads:  T1   T2   T3
                 \   |   /
                  \  |  /
                [ Kernel Thread K1 ]

One-to-One

  • Each user thread maps to its own kernel thread.

  • More concurrency, but higher overhead.

User Threads:  T1   T2   T3
                |    |    |
                v    v    v
           Kernel:   K1   K2   K3

Many-to-Many

  • Many user-level threads multiplexed over fewer or equal kernel threads.

  • Provides flexibility and concurrency.

User Threads:  T1   T2   T3   T4   T5
                 \   |   / \   |   /
                  \  |  /   \  |  /
              Kernel Threads:  K1   K2

Two-Level Model

  • Variation of many-to-many.

  • Allows binding some user threads directly to kernel threads.

User Threads:  T1   T2   T3   T4
                |   / \     |
                v  v   v    v
              Kernel Threads: K1   K2

Threading APIs

  • Pthreads (POSIX Threads) - Standard API for thread creation and synchronization in UNIX/Linux. - Functions for creating/joining threads, mutexes, condition variables.

  • Windows Threads - Windows API for multithreading. - Managed via functions like CreateThread, WaitForSingleObject.

  • Java Threads - Built-in support with Thread class and Runnable interface. - Managed by the Java Virtual Machine (JVM).

  • Other APIs - OpenMP: Directive-based parallelism for C/C++/Fortran. - C++11 <thread>: Standard threading library in modern C++.