Thread vs Process
- Thread: a lightweight process that can run concurrently with other threads within the same process.
- Process: a program in execution, which can contain multiple threads.
Thread Control Block (TCB)
Shared Info:
- Memory
- IO and Files
Per-Thread info:
- state
- PC, registers
-
execution stack
Thread State
stateDiagram-v2
Ready --> Running: schedule thread
Running --> Ready: timer interrupt, yield
Running --> Waiting: block for resource<br>(I/O, page fault, etc.)
Waiting --> Ready: resource free,<br>I/O completion interrupt
[*] --> Ready: create thread
Running --> [*]: thread exit
Thread Queue and Scheduling
- ready queue: threads that are ready to run, waiting for CPU time
- waiting queue: threads that are waiting for some event to occur (eg: I/O completion)
- current thread: the thread that is currently running on the CPU
- scheduler: the part of the OS that decides which thread to run next
- dispatcher: the part of the OS that switches between threads (context switch)
- context switch: the process of saving the state of the current thread and loading the state of the next thread to run -
- preemptive scheduling: the scheduler can interrupt a running thread to give CPU time to another thread (eg: timer interrupt)
- non-preemptive scheduling: the scheduler cannot interrupt a running thread, the thread must yield the CPU
voluntarily
yield()- voluntarily give up the CPU, context switch to another thread.@returnswhen another thread calledyield()sleep()- voluntarily give up the CPU for a specified amount of time