Download Lecture Slides on Processes and Parallel Programs | CSE 120 and more Study notes Computer Science in PDF only on Docsity!
CSE 120CSE 120
Principles of OperatingPrinciples of Operating
SystemsSystemsSystemsSystems
WinterWinter 2007 2007
Lecture 4: ThreadsLecture 4: Threads
Keith Marzullo and Geoffrey M. VoelkerKeith Marzullo and Geoffrey M. Voelker
AnnouncementsAnnouncements
z Homework #1 due now
zz Project 0 due tonightProject 0 due tonight
z Project groups
Please send project group info to Jeremy or Mike
Project 1 out (no time like the present)
January 18, 2007 CSE 120 – Lecture 4 – Threads 2
ProcessesProcesses
z Recall that a process includes many things
An address space (defining all the code and data pages)p ( g p g )
OS resources (e.g., open files) and accounting information
Execution state (PC, SP, regs, etc.)
z Creating a new process is costly because of all of the
data structures that must be allocated and initialized
Recall struct proc in Solaris
…which does not even include page tables, perhaps TLB
flushing etc
January 18, 2007 CSE 120 – Lecture 4 – Threads 3
flushing, etc.
z Communicating between processes is costly because
most communication goes through the OS
Overhead of system calls and copying data
Parallel ProgramsParallel Programs
z Also recall our Web server example that forks off copies
of itself to handle multiple simultaneous requestsof itself to handle multiple simultaneous requests
Or any parallel program that executes on a multiprocessor
z To execute these programs we need to
Create several processes that execute in parallel
Cause each to map to the same address space to share data
» They are all part of the same computation
Have the OS schedule these processes in parallel (logically or
January 18, 2007 CSE 120 – Lecture 4 – Threads 4
p p ( g y
physically)
z This situation is very inefficient
Space: PCB, page tables, etc.
Time: create data structures, fork and copy addr space, etc.
Threads in a ProcessThreads in a Process
Stack (T1) Thread 1
Heap
Stack (T2)
Stack (T3) Thread 3
Thread 2
January 18, 2007 CSE 120 – Lecture 4 – Threads 7
Code
Static Data
PC (T1)
PC (T3)
PC (T2)
Thread Design SpaceThread Design Space
One Thread/Process
Many Address Spaces
(Early Unix)
One Thread/Process
One Address Space
(MSDOS)
Address Space
Thread
January 18, 2007 CSE 120 – Lecture 4 – Threads 8
Many Threads/Process
Many Address Spaces
(Mach, Unix, NT, Chorus)
Many Threads/Process
One Address Space
(Pilot, Java)
Thread
Process/Thread SeparationProcess/Thread Separation
z Separating threads and processes makes it easier to
support multithreaded applicationssupport multithreaded applications
Creating concurrency does not require creating new processes
z Concurrency (multithreading) can be very useful
Improving program structure
Handling concurrent events (e.g., Web requests)
Writing parallel programs
z So multithreading is even useful on a uniprocessor
January 18, 2007 CSE 120 – Lecture 4 – Threads 9
z So multithreading is even useful on a uniprocessor
Threads: Concurrent ServersThreads: Concurrent Servers
z Using fork() to create new processes to handle
requests in parallel is overkill for such a simple taskrequests in parallel is overkill for such a simple task
z Recall our forking Web server:
while (1) {
int sock = accept();
if ((child_pid = fork()) == 0) {
Handle client request
January 18, 2007 CSE 120 – Lecture 4 – Threads 10
Close socket and exit
} else {
Close socket
Kernel Thread LimitationsKernel Thread Limitations
z Kernel-level threads make concurrency much cheaper
than processesthan processes
Much less state to allocate and initialize
z However, for fine-grained concurrency, kernel-level
threads still suffer from too much overhead
Thread operations still require system calls
» Ideally, want thread operations to be as fast as a procedure call
Kernel-level threads have to be general to support the needs
January 18, 2007 CSE 120 – Lecture 4 – Threads 13
g pp
of all programmers, languages, runtimes, etc.
z For such fine-grained concurrency, need even
“cheaper” threads
UserUser--Level ThreadsLevel Threads
z To make threads cheap and fast, they need to be
implemented at user levelimplemented at user level
Kernel-level threads are managed by the OS
User-level threads are managed entirely by the run-time
system (user-level library)
z User-level threads are small and fast
A thread is simply represented by a PC, registers, stack, and
small thread control block (TCB)
January 18, 2007 CSE 120 – Lecture 4 – Threads 14
Creating a new thread, switching between threads, and
synchronizing threads are done via procedure call
» No kernel involvement
User-level thread operations 100x faster than kernel threads
Small and Fast…Small and Fast…
z Nachos thread control block
class Thread {
int *stack;
int *stackTop;
int machineState[MachineStateSize];
ThreadStatus status;
char *name;
January 18, 2007 CSE 120 – Lecture 4 – Threads 15
U/L Thread LimitationsU/L Thread Limitations
z But, user-level threads are not a perfect solution
As with everything else they are a tradeoffAs with everything else, they are a tradeoff
z User-level threads are invisible to the OS
They are not well integrated with the OS
z As a result, the OS can make poor decisions
Scheduling a process with idle threads
Blocking a process whose thread initiated an I/O, even though
the process has other threads that can execute
January 18, 2007 CSE 120 – Lecture 4 – Threads 16
the process has other threads that can execute
Unscheduling a process with a thread holding a lock
z Solving this requires communication between the
kernel and the user-level thread manager
User and Kernel ThreadsUser and Kernel Threads
January 18, 2007 CSE 120 – Lecture 4 – Threads 19
Multiplexing user-level threads
on a single kernel thread for
each process
Multiplexing user-level threads
on multiple kernel threads for
each process
Implementing ThreadsImplementing Threads
z Implementing threads has a number of issues
InterfaceInterface
Context switch
Preemptive vs. non-preemptive
Scheduling
Synchronization (next lecture)
z Focus on user-level threads
Kernel-level threads are similar to original process
January 18, 2007 CSE 120 – Lecture 4 – Threads 20
Kernel level threads are similar to original process
management and implementation in the OS
What you will be dealing with in Nachos
Not only will you be using threads in Nachos, you will be
implementing more thread functionality
Thread InterfaceThread Interface
z thread_fork(procedure_t)
Create a new thread of controlCreate a new thread of control
Also thread_create(), thread_setstate()
z thread_stop()
Stop the calling thread; also thread_block
z thread_start(thread_t)
Start the given thread
thread yield()
January 18, 2007 CSE 120 – Lecture 4 – Threads 21
z thread_yield()
Voluntarily give up the processor
z thread_exit()
Terminate the calling thread; also thread_destroy
Thread SchedulingThread Scheduling
z The thread scheduler determines when a thread runs
zz It uses queues to keep track of what threads are doingIt uses queues to keep track of what threads are doing
Just like the OS and processes
But it is implemented at user-level in a library
z Run queue: Threads currently running (usually one)
z Ready queue: Threads ready to run
z Are there wait queues?
January 18, 2007 CSE 120 – Lecture 4 – Threads 22
How would you implement thread_sleep(time)?
Implementing thread_yield()Implementing thread_yield()
thread_yield() {
thread_t old_thread = current_thread;
current_thread = get_next_thread();
append_to_queue(ready_queue, old_thread);
context_switch(old_thread, current_thread);
return;
As old thread
As new thread
January 18, 2007 CSE 120 – Lecture 4 – Threads 25
z The magic step is invoking context_switch()
z Why do we need to call append_to_queue()?
Thread Context SwitchThread Context Switch
z The context switch routine does all of the magic
Saves context of the currently running thread (old thread)Saves context of the currently running thread (old_thread)
» Push all machine state onto its stack ( not its TCB)
Restores context of the next thread
» Pop all machine state from the next thread’s stack
The next thread becomes the current thread
Return to caller as new thread
z This is all done in assembly language
January 18, 2007 CSE 120 – Lecture 4 – Threads 26
It works at the level of the procedure calling convention, so it
cannot be implemented using procedure calls
See code/threads/switch.s in Nachos
Preemptive SchedulingPreemptive Scheduling
z Non-preemptive threads have to voluntarily give up CPU
A long-running thread will take over the machineA long running thread will take over the machine
Only voluntary calls to thread_yield(), thread_stop(), or
thread_exit() causes a context switch
z Preemptive scheduling causes an involuntary context
switch
Need to regain control of processor asynchronously
Use timer interrupt
January 18, 2007 CSE 120 – Lecture 4 – Threads 27
p
Timer interrupt handler forces current thread to “call” thread_yield
» How do you do this?
Nachos is preemptive
» See use of thread->yieldOnReturn in code/machine/interrupt.cc
Threads SummaryThreads Summary
z The operating system as a large multithreaded program
Each process executes as a thread within the OSEach process executes as a thread within the OS
z Multithreading is also very useful for applications
Efficient multithreading requires fast primitives
Processes are too heavyweight
z Solution is to separate threads from processes
Kernel-level threads much better, but still significant overhead
User level threads even better but not well integrated with OS
January 18, 2007 CSE 120 – Lecture 4 – Threads 28
User-level threads even better, but not well integrated with OS
z Now, how do we get our threads to correctly cooperate
with each other?
Synchronization…