COS 318: Operating Systems Processes and Threads
COS 318: Operating Systems Processes and Threads
http://www.cs.princeton.edu/courses/archive/fall11/cos318
Today’s Topics
Processes
Concurrency
Threads
Reminder:
Hope you’re all busy implementing your assignment
2
(Traditional) OS Abstractions
Processes - thread of control with context
main() main()
{ { heap
... ...
foo() foo()
... ...
} } stack
bar() bar()
{ { registers
... ...
} }
PC
Program Process
5
Process vs. Program
Process > program
Program is just part of process state
Example: many users can run the same program
• Each process has its own address space, i.e., even though
program has single set of variable names, each process will
have different values
Process < program
A program can invoke more than one process
Example: Fork off processes
6
Simplest Process
Sequential execution
No concurrency inside a process
Everything happens sequentially
Some coordination may be required
Process state
Registers
Main memory
I/O devices
• File system
• Communication ports
…
7
Process Abstraction
Unit of scheduling
One (or more*) sequential threads of control
program counter, register values, call stack
Unit of resource allocation
address space (code and data), open files
sometimes called tasks or jobs
Operations on processes: fork (clone-style creation),
wait (parent on child),
exit (self-termination), signal, kill.
Process Management
Fundamental task of any OS
How?
data structure for each process
describes state and resource ownership
Process Scheduling:
A Simple Two-State Model
program(s) to be executed
19
Primitives of Processes
Creation and termination
Exec, Fork, Wait, Kill
Signals
Action, Return, Handler
Operations
Block, Yield
Synchronization
We will talk about this later
20
Make A Process
Creation
Load code and data into memory
Create an empty call stack
Initialize state to same as after a process switch
Make the process ready to run
Clone
Stop current process and save state
Make copy of current code, data, stack and OS state
Make the process ready to run
21
Process Creation
Assign a new process ID
new entry in process table
Allocate space for process image
space for PCB
space for address space and user stack
Initialize PCB
ID of process, parent
PC set to program entry point
typically, “ready” state
Linkages and other DS
place image in list/queue
accounting DS
If ((pid = fork()) == 0) {
/* child process */
exec(“foo”); /* does not return */
else
/* parent */
wait(pid); /* wait for child to die */
23
Concurrency and Process
Concurrency
Hundreds of jobs going on in a system
CPU is shared, as are I/O devices
Each job would like to have its own computer
Process concurrency
Decompose complex problems into simple ones
Make each simple one a process
Deal with one at a time
Each process feels like having its own computer
24
Process Parallelism
Virtualization
Each process run for a while emacs emacs
Make a CPU into many
gcc
Each virtually has its own CPU
I/O parallelism
CPU job overlaps with I/O CPU I/O CPU
Each runs almost as fast as if it 3s 2s 3s
9s
has its own computer CPU I/O
Reduce total completion time 3s 2s
CPU parallelism
CPU
Multiple CPUs (such as SMP) 3s
Processes running in parallel 3s
CPU
Speedup 3s
25
More on Process Parallelism
Process parallelism is common in real life
Each sales person sell $1M annually
Hire 100 sales people to generate $100M revenue
Speedup
Ideal speedup is factor of N
Reality: bottlenecks + coordination overhead
Question
Can you speedup by working with a partner?
Can you speedup by working with 20 partners?
Can you get super-linear (more than a factor of N) speedup?
26
Process-related System Calls
Simple and powerful primitives for process
creation and initialization.
Unix fork creates a child process as (initially) a clone of the parent
[Linux: fork() implemented by clone() system call]
parent program runs in child process – maybe just to set it up for
exec
child can exit, parent can wait for child to do so.
[Linux: wait4 system call]
Rich
facilities for controlling processes by
asynchronous signals.
notification of internal and/or external events to processes or groups
the look, feel, and power of interrupts and exceptions
default actions: stop process, kill process, dump core, no effect
user-level handlers
Process Control
if (pid = fork()) {
/* parent */ Parent uses wait to sleep
….. until the child exits; wait
pid = wait(&status); returns child pid and
} else { status.
/* child */
….. Wait variants allow wait
exit(status); on a specific child, or
} notification of stops and
other signals.
Child process passes
status back to parent on
exit, to report success/
failure.
Child Discipline
After a fork, the parent program (not process) has
complete control over the behavior of its child process.
The child inherits its execution environment from the
parent...but the parent program can change it.
sets bindings of file descriptors with open, close, dup
pipe sets up data channels between processes
Parent program may cause the child to execute a
different program, by calling exec* in the child context.
Fork/Exit/Wait Example
OS resources
exit(status);
Exit with status, destroying the
process.
wait exit
int pid = wait*(&status);
Wait for exit (or other status change)
of a child.
Join Scenarios
Several cases must be considered for join
(e.g., exit/wait).
What if the child exits before the parent does the wait?
• “Zombie” process object holds child status and stats.
What if the parent continues to run but never joins?
• Danger of filling up memory with zombie processes?
• Parent might have specified it was not going to wait or that it
would ignore its child’s exit. Child status can be discarded.
What if the parent exits before the child?
• Orphans become children of init (process 1).
What if the parent can’t afford to get “stuck” on a join?
• Asynchronous notification (we’ll see an example later).
Linux Processes
Processes and threads are not differentiated – with
varying degrees of shared resources
clone() system call takes flags to determine what
resources parent and child processes will share:
Open files
Signal handlers
Address space
Same parent
Process Context Switch
Save a context (everything that a process may damage)
All registers (general purpose and floating point)
All co-processor state
Save all memory to disk?
What about cache and TLB stuff?
Start a context
Does the reverse
Challenge
OS code must save state without changing any state
How to run without touching any registers?
• CISC machines have a special instruction to save and restore all
registers on stack
• RISC: reserve registers for kernel or have way to carefully save
one and then continue
35
Today’s Topics
Processes
Concurrency
Threads
36
Before Threads…
Recall that a process consists of:
program(s)
data
stack
PCB
all stored in the process image
resource ownership
• address space to hold process image
• I/O devices, files, etc.
execution
• a single execution path (thread of control)
• execution state, PC & registers, stack
Refining Terminology
Distinguish the two characteristics
process: resource ownership
thread: unit of execution (dispatching)
• AKA lightweight process (LWP)
40
Threads and Processes
Decouple the resource allocation aspect from the
control aspect
Thread abstraction - defines a single sequential
instruction stream (PC, stack, register values)
Process - the resource context serving as a “container”
for one or more threads (shared address space)
Process vs. Threads
Address space
Processes do not usually share memory
Process context switch changes page table and other memory
mechanisms
Threads in a process share the entire address space
Privileges
Processes have their own privileges (file accesses, e.g.)
Threads in a process share all privileges
Question
Do you really want to share the “entire” address space?
42
An Example
Thread Thread
doc
Editing thread:
Responding to
Address Space Autosave thread:
your typing in periodically
your doc writes your doc
file to disk
Thread Control Block (TCB)
State
• Ready: ready to run
• Running: currently running
• Blocked: waiting for resources
Registers
Status(EFLAGS)
Program counter (EIP)
Stack
Code
44
Typical Thread API
Creation
Create, Join, Exit
Mutual exclusion
Acquire (lock), Release (unlock)
Condition variables
Wait, Signal, Broadcast
45
Thread Context Switch
Save a context (everything that a thread may damage)
All registers (general purpose and floating point)
All co-processor state
Need to save stack?
What about cache and TLB stuff?
Start a context
Does the reverse
May trigger a process context switch
46
Procedure Call
Caller or callee save some context (same stack)
Caller saved example:
47
Threads vs. Procedures
Threads may resume out of order
Cannot use LIFO stack to save state
Each thread has its own stack
Threads switch less often
Do not partition registers
Each thread “has” its own CPU
Threads can be asynchronous
Procedure call can use compiler to save state synchronously
Threads can run asynchronously
Multiple threads
Multiple threads can run on multiple CPUs in parallel
Procedure calls are sequential
48
Multi-Threaded Environment
Process:
virtual address space (for image)
protected access to resources
• processors, other processes, I/O, files
User-Level Kernel-Level
User-Level Threads
Thread management done by an application
Disadvantages:
if one thread blocks, all are blocked (process switch)
• e.g., I/O, page faults
cannot take advantage of multiprocessor
• one process to one processor
programmers usually want threads for blocking apps
Kernel-Level Threads
Thread management done by kernel
process as a whole (process table)
individual threads (thread table)
Disadvantage of KLT:
thread switch causes mode switch to kernel
Real Operating Systems
One or many address spaces
One or many threads per address space
60
Summary
Concurrency
CPU and I/O
Among applications
Within an application
Processes
Abstraction for application concurrency
Threads
Abstraction for concurrency within an application
61
Unix Signals
int alarmflag=0;
alarmHandler ()
{ printf(“An alarm clock signal was received\n”);
alarmflag = 1;
} Instructs kernel
main() Sets up signal handler to
{ send SIGALRM
signal (SIGALRM, alarmHandler); in
alarm(3); printf(“Alarm has been set\n”); 3 seconds
while (!alarmflag) pause ();
printf(“Back from alarm signal handler\n”); Suspends caller
} until signal
User’s View of Signals II
main()
{
int (*oldHandler) ();
printf (“I can be control-c’ed\n”);
sleep (3);
oldHandler = signal (SIGINT, SIG_IGN);
printf(“I’m protected from control-c\n”);
sleep(3);
signal (SIGINT, oldHandler);
printf(“Back to normal\n”);
sleep(3); printf(“bye\n”);
}
Yet Another User’s View
Terminate
Running
Resource becomes
available
69