Overview
What is a Thread?
- Thread is a basic unit of CPU utilization
- Comprised of a thread ID, program counter, register set, and stack.
- Shares code section, data section, and other OS resources (eg. open files, signals) with sibling threads
Motivation
- An application may be required to perform several similar tasks
- For example: a busy web server has many clients concurrently making requests
- Running as a single-threaded process only allows 1 client to be serviced at a time
- Solution: one process listens for requests, fork process for each incoming request
- Not best solution
- Process creation is time consuming and resource intensive
- Better solution: use multithreaded process instead
- Server has one thread listening for requests
- When server accepts a request, create a new thread to service that request
Benefits
- Responsiveness
- Evident in interactive applications
- User clicks a button to perform a heavy computation. One thread keeps the UI responsive while another thread performs the computation asynchronously
- Resource sharing
- Threads share the resources of belonging process by default
- Processes can only share resources through special techniques like shared memory, message passing
- Economy
- Threads share resources of belonging process, reducing overhead
- Thread creation takes less time and uses less memory than process creation
- Context switching between threads is faster than processes
- Scalability
- Scales well to multiprocessor system—threads can run in parallel on different CPUs
- Single-threaded application in the same environment can still only run on 1 CPU
Multicore Programming
- Single-CPU systems evolved into multi-CPU systems
- Multi-CPU evolved into multicore systems
- each processing chip has multiple cores
- each core appears as a separate CPU to the OS