Threads
Threads
Slide courtesy:
Chester Rebeiro
IIT Madras 1
Processes
• Separate streams of execution
• Each process isolated from the
other
• Process state contains
– Process ID
– Environment
– Working directory.
– Program instructions
– Registers
– Stack
– Heap
– File descriptors
• Created by the OS using fork
– Significant overheads
2
Threads
• Separate streams of execution
within a single process
• Threads in a process not isolated
from each other
• Each thread state (thread control
block) contains
– Registers (including EIP, ESP)
– stack
3
Why threads?
• Lightweight
4
Threads vs Processes
• A thread has no data • A process has code, heap,
segment or heap stack, other segments
• A thread cannot live on its • A process has at-least one
own. It needs to be thread.
attached to a process
• There can be more than • Threads within a process
one thread in a process. share the same I/O, code,
Each thread has its own files.
stack
• If a thread dies, its stack is • If a process dies, all threads
reclaimed die.
Based on Junfeng Yang’s lecture slides
http://www.cs.columbia.edu/~junfeng/13fa-w4118/lectures/l08-thread.pdf
5
pthread library
Thread identifier (TID) much like
• Create a thread in a process
int pthread_create(pthread_t *thread, Pointer to a function,
const pthread_attr_t *attr, which starts execution in a
different thread
void *(*start_routine) (void *),
void *arg);
Arguments to the function
6
pthread library contd.
• Join : Wait for a specific thread to complete
7
Example
How many threads are there in this
program? 3
8
Example
main
join(t1) t1
t2
join(t2)