Introduction
A thread is the smallest unit of a program that can be scheduled for execution.
Threads enable concurrent execution within a single process, allowing a program
to perform multiple tasks simultaneously. Threads are sometimes referred to as
lightweight processes, as they share the same memory space but operate
independently.
Why Use Threads?
Improved Performance: Threads enable better utilization of multi-core
processors by performing tasks in parallel.
Simplified Design for Concurrency: Programs can divide tasks into smaller
threads to handle multiple tasks simultaneously.
Responsiveness: Applications like GUIs remain responsive while performing
background tasks.
Resource Sharing: Threads within the same process share memory and
other resources, reducing overhead compared to creating separate
processes.
Thread Components
A thread consists of:
1. Thread ID: A unique identifier for the thread.
2. Program Counter: Tracks the thread's current execution point.
3. Registers: Hold the thread's current working variables.
4. Stack: Stores the execution history, including function calls and local
variables.
, Multithreading
Multithreading refers to the ability of a CPU to execute multiple threads
concurrently, improving program efficiency and responsiveness. Modern
operating systems support multithreading at both user and kernel levels.
Types of Threads
1. User Threads:
o Managed by user-level libraries rather than the kernel.
o Faster to create and manage.
o Limited by the kernel's inability to recognize user threads directly.
2. Kernel Threads:
o Managed directly by the operating system kernel.
o Fully supported by the OS, allowing better utilization of system
resources.
o Slightly more overhead due to kernel involvement.
Thread Models
Operating systems use different models to map user threads to kernel threads:
1. Many-to-One Model:
o Maps multiple user threads to a single kernel thread.
o Efficient but does not support true parallel execution on multi-core
processors.
2. One-to-One Model:
o Maps each user thread to a separate kernel thread.
o Provides true parallelism but can be resource-intensive due to the
large number of kernel threads.
3. Many-to-Many Model:
o Maps many user threads to an equal or smaller number of kernel
threads.