Lec17 Threads Introduction
Lec17 Threads Introduction
Operating System
Lec17-Threads Introduction
Reference
• Modern Operating System
2.2.1 The Thread Model
2.2.2 Thread Usage
Andrew S. Tanenbaum
2nd edition
2
Thread: Introduction
• Each process has
1. Own Address Space
2. Single thread of control
• A process model has two concepts:
1. Resource grouping
2. Execution
• Sometimes it is useful to separate them
3
Unit of Resource Ownership
• A process has an
Address space
Open files
Child processes
Accounting information
Signal handlers
Etc
• If these are put together in a form of a process,
can be managed more easily
4
Unit of Dispatching
• Path of execution
Program counter: which instruction is running
Registers:
• holds current working variables
Stack:
• Contains the execution history, with one entry for each procedure
called but not yet returned
State
• Processes are used to group resources together
• Threads are the entities scheduled for execution on
the CPU
• Threads are also called lightweight process 5
Its better to distinguish between
theAddress
two concepts
Heavy weight process
space/Global
Variables
Open files
Child processes
Accounting info
Signal handlers
Program counter
Registers In case of multiple
Stack threads per process
Unit of Resource State
Split Unit of Dispatch
Program
Address
counterProgram
space/Global
Registers
counter
Variables
Stack Registers
Program
Open files
State Stackcounter
Child processes
Accounting info Share State Registers 6
Stack
Signal handlers
Threads
• Allow multiple execution paths in the same
process environment
• Threads share address space, open files etc
• But have own set of Program counter, Stack
etc
• The first thread starts execution with
int main(int argc, char *argv[])
• The threads appear to the Scheduling part of
an OS just like any other process
7
Process Vs. Threads
14
2. Background Processing
• Consider writing a GUI-based application that uses:
• Mouse
• Keyboard input
• Handles various clock-based events
• In a single threaded application, if the application is
busy with one activity, it cannot respond (quickly
enough) to other events, such as mouse or keyboard
input.
• Handling such concurrency is difficult and complex
• But simple in a multithreaded process
15
e.g. A word processor with 3
threads
16
3. Parallel Algorithms e.g. Merge
Sort
18
Benefits of Threads
• Since threads within the same process share
memory and files, they can communicate with
each other without invoking the kernel
• Therefore necessary to synchronize the
activities of various threads so that they do not
obtain inconsistent views of the data
19
Example of inconsistent view
• 3 variables: A, B, C which are shared by
thread T1 and thread T2
• T1 computes C = A+B
• T2 transfers amount X from A to B
T2 must do: A = A -X and B = B+X (so that
A+B is unchanged)
• But if T1 computes A+B after T2 has done A =
A-X but before B = B+X
• then T1 will not obtain the correct result for C
=A+B
20