Operating Systems 7
Operating Systems 7
Lecture # 7
Thread Concept
A thread is a “lightweight” process
which executes within the address
space of a process.
A thread can be scheduled to run on
a CPU as an independent unit and
terminate.
Multiple threads can run
simultaneously.
Thread Concept
Threads have their own
Thread ID
CPU context (PC, SP, register set,
etc.)
Stack
Priority
errno
Thread Concept
Threads share
Code and data
Open files
Current working directory
User and group IDs
Signal setups and handlers
PCB
Single and Multithreaded
Processes
Threads are Similar to
Processes
A thread can be in states similar to
a process (new, ready, running,
blocked, terminated)
A thread can create another thread
Threads are Different from
Processes
Multiple threads can operate within
the same address space
No “automatic” protection
mechanism is in place for threads—
they are meant to help each other
Advantages of Threads
Responsiveness
Multi-threaded servers (e.g.,
browsers) can allow interaction
with user while a thread is
formulating response to a
previous user query (e.g.,
rendering a web page)
Advantages of Threads
Resource sharing
Process resources (code, data,
etc.)
OS resources (PCB, PPFDT, etc.)
Advantages of Threads
Economy
Take less time to create, schedule,
and terminate
Solaris 2: thread creation is 30
times faster than process creation
and thread switching is five times
faster than process switching
Advantages of Threads
Performance in multi-processor
and multi-threaded architectures
(e.g., Intel’s P4 HT)
Multiple threads can run
simultaneously
Disadvantages of Threads
Resource sharing—
synchronization needed
between threads
Difficult to write and debug
multi-threaded programs
Single-Threaded Process
main()
{ Thread
…
f1(…);
… f1
f2(…);
…
}
f2
f1(…)
{ … }
f2(…)
{ … } Process
Terminated
Multi-Threaded Process
main()
{ Process Address Space
…
thread(t1,f1); main t1 t2
…
thread(t2,f2); PC
…
PC
}
f1(…) PC
{ … }
f2(…)
{ … }
User Threads
Thread management done by user-
level threads libraries
Kernel not aware of threads
CPU not interrupted during thread
switching
A system call by a thread blocks the
whole process
Fair scheduling: P1 has one thread and
P2 has 100 threads
User Threads
Examples
POSIX Pthreads
Mach C-threads
Solaris 2 threads
Kernel Threads
Thread management done by
kernel
Kernel aware of threads
CPU switched during context
switching
A system call does not block the
whole process
Fair scheduling: P1 has one thread
and P2 has 100
Kernel Threads
Examples
Windows NT/2000
Solaris 2
Linux