CS162 Operating Systems and Systems Programming Lecture 5 Cooperating Threads September 14, 2009 Prof. John Kubiatowicz

Slides:



Advertisements
Similar presentations
Chapter 3 Process Description and Control
Advertisements

CS162 Operating Systems and Systems Programming Lecture 5 Cooperating Threads February 1, 2006 Prof. Anthony D. Joseph
CMPT 300: Operating Systems I Dr. Mohamed Hefeeda
Processes CSCI 444/544 Operating Systems Fall 2008.
1 School of Computing Science Simon Fraser University CMPT 300: Operating Systems I Dr. Mohamed Hefeeda.
CS162 Operating Systems and Systems Programming Lecture 5 Cooperating Threads September 14, 2005 Prof. John Kubiatowicz
3.5 Interprocess Communication Many operating systems provide mechanisms for interprocess communication (IPC) –Processes must communicate with one another.
Threads 1 CS502 Spring 2006 Threads CS-502 Spring 2006.
3.5 Interprocess Communication
Silberschatz, Galvin and Gagne ©2009 Operating System Concepts – 8 th Edition, Chapter 3: Processes.
Process Concept An operating system executes a variety of programs
CPS110: Implementing threads/locks on a uni-processor Landon Cox.
1 Process Description and Control Chapter 3 = Why process? = What is a process? = How to represent processes? = How to control processes?
Threads CS 416: Operating Systems Design, Spring 2001 Department of Computer Science Rutgers University
1 Threads Chapter 4 Reading: 4.1,4.4, Process Characteristics l Unit of resource ownership - process is allocated: n a virtual address space to.
Chapter 51 Threads Chapter 5. 2 Process Characteristics  Concept of Process has two facets.  A Process is: A Unit of resource ownership:  a virtual.
CSE 451: Operating Systems Autumn 2013 Module 6 Review of Processes, Kernel Threads, User-Level Threads Ed Lazowska 570 Allen.
Operating Systems CSE 411 CPU Management Sept Lecture 11 Instructor: Bhuvan Urgaonkar.
Silberschatz, Galvin and Gagne ©2009 Operating System Concepts – 8 th Edition, Chapter 4: Threads.
Chapter 4: Threads. 4.2CSCI 380 Operating Systems Chapter 4: Threads Overview Multithreading Models Threading Issues Pthreads Windows XP Threads Linux.
1 Lecture 4: Threads Operating System Fall Contents Overview: Processes & Threads Benefits of Threads Thread State and Operations User Thread.
Silberschatz, Galvin and Gagne ©2011Operating System Concepts Essentials – 8 th Edition Chapter 4: Threads.
Threads Many software packages are multi-threaded Web browser: one thread display images, another thread retrieves data from the network Word processor:
Implementing Processes and Process Management Brian Bershad.
Operating Systems Lecture 2 Processes and Threads Adapted from Operating Systems Lecture Notes, Copyright 1997 Martin C. Rinard. Zhiqing Liu School of.
Chapter 41 Processes Chapter 4. 2 Processes  Multiprogramming operating systems are built around the concept of process (also called task).  A process.
COSC 3407: Operating Systems Lecture 5: Independent Vs. Cooperating Threads.
Lecture 3 Process Concepts. What is a Process? A process is the dynamic execution context of an executing program. Several processes may run concurrently,
Silberschatz, Galvin and Gagne  2002 Modified for CSCI 399, Royden, Operating System Concepts Operating Systems Lecture 13 Threads Read Ch 5.1.
Multiprogramming. Readings r Silberschatz, Galvin, Gagne, “Operating System Concepts”, 8 th edition: Chapter 3.1, 3.2.
Scheduling Lecture 6. What is Scheduling? An O/S often has many pending tasks. –Threads, async callbacks, device input. The order may matter. –Policy,
CS 162 Discussion Section Week 2. Who am I? Haoyuan (HY) Li Office Hours: 1pm-3pm
CS 162 Discussion Section Week 2. Who am I? Wesley Chow Office Hours: 12pm-2pm 411 Soda Does Monday 1-3 work for everyone?
CS333 Intro to Operating Systems Jonathan Walpole.
CS162 Operating Systems and Systems Programming Lecture 3 Concurrency and Thread Dispatching September 7 th, 2011 Anthony D. Joseph and Ion Stoica
Lecture 5: Threads process as a unit of scheduling and a unit of resource allocation processes vs. threads what to program with threads why use threads.
CS 162 Discussion Section Week 2 (9/16 – 9/20). Who am I? Kevin Klues Office Hours:
1 Computer Systems II Introduction to Processes. 2 First Two Major Computer System Evolution Steps Led to the idea of multiprogramming (multiple concurrent.
Chapter 4: Multithreaded Programming. 4.2 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts What is Thread “Thread is a part of a program.
Operating Systems CSE 411 CPU Management Sept Lecture 10 Instructor: Bhuvan Urgaonkar.
Department of Computer Science and Software Engineering
Processes, Threads, and Process States. Programs and Processes  Program: an executable file (before/after compilation)  Process: an instance of a program.
© Janice Regan, CMPT 300, May CMPT 300 Introduction to Operating Systems Operating Systems Processes and Threads.
Processes & Threads Introduction to Operating Systems: Module 5.
Goals for Today How do we provide multiprogramming? What are Processes? How are they related to Threads and Address Spaces? Note: Some slides and/or pictures.
Operating System Concepts
Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8 th Edition Chapter 4: Threads.
1 Module 3: Processes Reading: Chapter Next Module: –Inter-process Communication –Process Scheduling –Reading: Chapter 4.5, 6.1 – 6.3.
Threads prepared and instructed by Shmuel Wimer Eng. Faculty, Bar-Ilan University 1July 2016Processes.
Processes and Threads Chapter 3 and 4 Operating Systems: Internals and Design Principles, 6/E William Stallings Patricia Roy Manatee Community College,
Multiprogramming. Readings r Chapter 2.1 of the textbook.
Processes and threads.
Process concept.
CS 6560: Operating Systems Design
CSCI 511 Operating Systems Ch3, 4 (Part C) Cooperating Threads
CSCS 511 Operating Systems Ch3, 4 (Part B) Further Understanding Threads Dr. Frank Li Skipped sections 3.5 & 3.6 
Lecture Topics: 11/1 Processes Process Management
CS399 New Beginnings Jonathan Walpole.
CS162 Operating Systems and Systems Programming Lecture 4 Cooperating Threads February 4, 2008 Prof. Anthony D. Joseph
CS162 Operating Systems and Systems Programming Lecture 5 Cooperating Threads September 15, 2010 Prof. John Kubiatowicz
February 2, 2009 Ion Stoica CS162 Operating Systems and Systems Programming Lecture 5 Cooperating Threads February.
CSCI 511 Operating Systems Ch3, 4 (Part B) Further Understanding Threads Dr. Frank Li Skipped sections 3.5 & 3.6 
CSCI 511 Operating Systems Ch3, 4 (Part C) Cooperating Threads
ICS 143 Principles of Operating Systems
Process & its States Lecture 5.
CS162 Operating Systems and Systems Programming Lecture 5 Cooperating Threads September 15, 2008 Prof. John Kubiatowicz
Lecture Topics: 11/1 General Operating System Concepts Processes
Process Description and Control
Anthony D. Joseph and Ion Stoica
CS510 Operating System Foundations
Presentation transcript:

CS162 Operating Systems and Systems Programming Lecture 5 Cooperating Threads September 14, 2009 Prof. John Kubiatowicz

Lec 5.2 9/14/09Kubiatowicz CS162 ©UCB Fall 2009 Review: Per Thread State Each Thread has a Thread Control Block (TCB) –Execution State: CPU registers, program counter, pointer to stack –Scheduling info: State (more later), priority, CPU time –Accounting Info –Various Pointers (for implementing scheduling queues) –Pointer to enclosing process? (PCB)? –Etc (add stuff as you find a need) OS Keeps track of TCBs in protected memory –In Arrays, or Linked Lists, or … Other State TCB 9 Link Registers Other State TCB 6 Link Registers Other State TCB 16 Link Registers Head Tail Ready Queue

Lec 5.3 9/14/09Kubiatowicz CS162 ©UCB Fall 2009 Review: Yielding through Internal Events Blocking on I/O –The act of requesting I/O implicitly yields the CPU Waiting on a “signal” from other thread –Thread asks to wait and thus yields the CPU Thread executes a yield() –Thread volunteers to give up CPU computePI() { while(TRUE) { ComputeNextDigit(); yield(); } –Note that yield() must be called by programmer frequently enough!

Lec 5.4 9/14/09Kubiatowicz CS162 ©UCB Fall 2009 Review: Stack for Yielding Thread How do we run a new thread? run_new_thread() { newThread = PickNewThread(); switch(curThread, newThread); ThreadHouseKeeping(); /* Later in lecture */ } How does dispatcher switch to a new thread? –Save anything next thread may trash: PC, regs, stack –Maintain isolation for each thread yield ComputePI Stack growth run_new_thread kernel_yield Trap to OS switch

Lec 5.5 9/14/09Kubiatowicz CS162 ©UCB Fall 2009 Review: Two Thread Yield Example Consider the following code blocks: proc A() { B(); } proc B() { while(TRUE) { yield(); } Suppose we have 2 threads: –Threads S and T Thread S Stack growth A B(while) yield run_new_thread switch Thread T A B(while) yield run_new_thread switch

Lec 5.6 9/14/09Kubiatowicz CS162 ©UCB Fall 2009 Goals for Today More on Interrupts Thread Creation/Destruction Cooperating Threads Note: Some slides and/or pictures in the following are adapted from slides ©2005 Silberschatz, Galvin, and Gagne Note: Some slides and/or pictures in the following are adapted from slides ©2005 Silberschatz, Galvin, and Gagne. Many slides generated from my lecture notes by Kubiatowicz.

Lec 5.7 9/14/09Kubiatowicz CS162 ©UCB Fall 2009 Interrupt Controller Interrupts invoked with interrupt lines from devices Interrupt controller chooses interrupt request to honor –Mask enables/disables interrupts –Priority encoder picks highest enabled interrupt –Software Interrupt Set/Cleared by Software –Interrupt identity specified with ID line CPU can disable all interrupts with internal flag Non-maskable interrupt line (NMI) can’t be disabled Network IntID Interrupt Interrupt Mask Control Software Interrupt NMI CPU Priority Encoder Timer Int Disable

Lec 5.8 9/14/09Kubiatowicz CS162 ©UCB Fall 2009 Example: Network Interrupt Disable/Enable All Ints  Internal CPU disable bit –RTI reenables interrupts, returns to user mode Raise/lower priority: change interrupt mask Software interrupts can be provided entirely in software at priority switching boundaries  add $r1,$r2,$r3 subi $r4,$r1,#4 slli $r4,$r4,#2 PC saved Disable All Ints Supervisor Mode Restore PC User Mode Raise priority Reenable All Ints Save registers Dispatch to Handler  Transfer Network Packet from hardware to Kernel Buffers  Restore registers Clear current Int Disable All Ints Restore priority RTI “Interrupt Handler” lw$r2,0($r4) lw$r3,4($r4) add$r2,$r2,$r3 sw8($r4),$r2  External Interrupt Pipeline Flush

Lec 5.9 9/14/09Kubiatowicz CS162 ©UCB Fall 2009 Review: Preemptive Multithreading Use the timer interrupt to force scheduling decisions Timer Interrupt routine: TimerInterrupt() { DoPeriodicHouseKeeping(); run_new_thread(); } This is often called preemptive multithreading, since threads are preempted for better scheduling –Solves problem of user who doesn’t insert yield(); Some Routine run_new_thread TimerInterrupt Interrupt switch Stack growth

Lec /14/09Kubiatowicz CS162 ©UCB Fall 2009 Administrivia Need group in section 101 to add member –We have a student that is unattached Information about Subversion on Handouts page –Make sure to take a look Other things on Handouts page –Synchronization examples/Interesting papers –Previous finals/solutions Sections in this class are mandatory –Make sure that you go to the section that you have been assigned! Reader is available at Copy Central on Hearst Should be reading Nachos code by now! –Get working on the first project –Set up regular meeting times with your group –Try figure out group interaction problems early on

Lec /14/09Kubiatowicz CS162 ©UCB Fall 2009 Review: Lifecycle of a Thread (or Process) As a thread executes, it changes state: –new: The thread is being created –ready: The thread is waiting to run –running: Instructions are being executed –waiting: Thread waiting for some event to occur –terminated: The thread has finished execution “Active” threads are represented by their TCBs –TCBs organized into queues based on their state

Lec /14/09Kubiatowicz CS162 ©UCB Fall 2009 ThreadFork(): Create a New Thread ThreadFork() is a user-level procedure that creates a new thread and places it on ready queue –We called this CreateThread() earlier Arguments to ThreadFork() –Pointer to application routine (fcnPtr) –Pointer to array of arguments (fcnArgPtr) –Size of stack to allocate Implementation –Sanity Check arguments –Enter Kernel-mode and Sanity Check arguments again –Allocate new Stack and TCB –Initialize TCB and place on ready list (Runnable).

Lec /14/09Kubiatowicz CS162 ©UCB Fall 2009 How do we initialize TCB and Stack? Initialize Register fields of TCB –Stack pointer made to point at stack –PC return address  OS (asm) routine ThreadRoot() –Two arg registers (a0 and a1) initialized to fcnPtr and fcnArgPtr, respectively Initialize stack data? –No. Important part of stack frame is in registers (ra) –Think of stack frame as just before body of ThreadRoot() really gets started ThreadRoot stub Initial Stack Stack growth

Lec /14/09Kubiatowicz CS162 ©UCB Fall 2009 How does Thread get started? Eventually, run_new_thread() will select this TCB and return into beginning of ThreadRoot() –This really starts the new thread Stack growth A B(while) yield run_new_thread switch ThreadRoot Other Thread ThreadRoot stub New Thread

Lec /14/09Kubiatowicz CS162 ©UCB Fall 2009 What does ThreadRoot() look like? ThreadRoot() is the root for the thread routine: ThreadRoot() { DoStartupHousekeeping(); UserModeSwitch(); /* enter user mode */ Call fcnPtr(fcnArgPtr); ThreadFinish(); } Startup Housekeeping –Includes things like recording start time of thread –Other Statistics Stack will grow and shrink with execution of thread Final return from thread returns into ThreadRoot() which calls ThreadFinish() –ThreadFinish() will start at user-level ThreadRoot Running Stack Stack growth Thread Code

Lec /14/09Kubiatowicz CS162 ©UCB Fall 2009 What does ThreadFinish() do? Needs to re-enter kernel mode (system call) “Wake up” (place on ready queue) threads waiting for this thread –Threads (like the parent) may be on a wait queue waiting for this thread to finish Can’t deallocate thread yet –We are still running on its stack! –Instead, record thread as “waitingToBeDestroyed” Call run_new_thread() to run another thread: run_new_thread() { newThread = PickNewThread(); switch(curThread, newThread); ThreadHouseKeeping(); } –ThreadHouseKeeping() notices waitingToBeDestroyed and deallocates the finished thread’s TCB and stack

Lec /14/09Kubiatowicz CS162 ©UCB Fall 2009 Additional Detail Thread Fork is not the same thing as UNIX fork –UNIX fork creates a new process so it has to create a new address space –For now, don’t worry about how to create and switch between address spaces Thread fork is very much like an asynchronous procedure call –Runs procedure in separate thread –Calling thread doesn’t wait for finish What if thread wants to exit early? –ThreadFinish() and exit() are essentially the same procedure entered at user level

Lec /14/09Kubiatowicz CS162 ©UCB Fall 2009 Parent-Child relationship Every thread (and/or Process) has a parentage –A “parent” is a thread that creates another thread –A child of a parent was created by that parent Typical process tree for Solaris system

Lec /14/09Kubiatowicz CS162 ©UCB Fall 2009 ThreadJoin() system call One thread can wait for another to finish with the ThreadJoin(tid) call –Calling thread will be taken off run queue and placed on waiting queue for thread tid Where is a logical place to store this wait queue? –On queue inside the TCB Similar to wait() system call in UNIX –Lets parents wait for child processes Other State TCB 9 Link Registers Other State TCB 6 Link Registers Other State TCB 16 Link Registers Head Tail Termination Wait queue TCB tid

Lec /14/09Kubiatowicz CS162 ©UCB Fall 2009 Use of Join for Traditional Procedure Call A traditional procedure call is logically equivalent to doing a ThreadFork followed by ThreadJoin Consider the following normal procedure call of B() by A(): A() { B(); } B() { Do interesting, complex stuff } The procedure A() is equivalent to A’(): A’() { tid = ThreadFork(B,null); ThreadJoin(tid); } Why not do this for every procedure? –Context Switch Overhead –Memory Overhead for Stacks

Lec /14/09Kubiatowicz CS162 ©UCB Fall 2009 Kernel versus User-Mode threads We have been talking about Kernel threads –Native threads supported directly by the kernel –Every thread can run or block independently –One process may have several threads waiting on different things Downside of kernel threads: a bit expensive –Need to make a crossing into kernel mode to schedule Even lighter weight option: User Threads –User program provides scheduler and thread package –May have several user threads per kernel thread –User threads may be scheduled non-premptively relative to each other (only switch on yield()) –Cheap Downside of user threads: –When one thread blocks on I/O, all threads block –Kernel cannot adjust scheduling among all threads –Option: Scheduler Activations »Have kernel inform user level when thread blocks…

Lec /14/09Kubiatowicz CS162 ©UCB Fall 2009 Threading models mentioned by book Simple One-to-One Threading Model Many-to-One Many-to-Many

Lec /14/09Kubiatowicz CS162 ©UCB Fall 2009 Multiprocessing vs Multiprogramming Remember Definitions: –Multiprocessing  Multiple CPUs –Multiprogramming  Multiple Jobs or Processes –Multithreading  Multiple threads per Process What does it mean to run two threads “concurrently”? –Scheduler is free to run threads in any order and interleaving: FIFO, Random, … –Dispatcher can choose to run each thread to completion or time-slice in big chunks or small chunks ABC BAACBCB Multiprogramming A B C Multiprocessing

Lec /14/09Kubiatowicz CS162 ©UCB Fall 2009 Correctness for systems with concurrent threads If dispatcher can schedule threads in any way, programs must work under all circumstances –Can you test for this? –How can you know if your program works? Independent Threads: –No state shared with other threads –Deterministic  Input state determines results –Reproducible  Can recreate Starting Conditions, I/O –Scheduling order doesn’t matter (if switch() works!!!) Cooperating Threads: –Shared State between multiple threads –Non-deterministic –Non-reproducible Non-deterministic and Non-reproducible means that bugs can be intermittent –Sometimes called “Heisenbugs”

Lec /14/09Kubiatowicz CS162 ©UCB Fall 2009 Interactions Complicate Debugging Is any program truly independent? –Every process shares the file system, OS resources, network, etc –Extreme example: buggy device driver causes thread A to crash “independent thread” B You probably don’t realize how much you depend on reproducibility: –Example: Evil C compiler »Modifies files behind your back by inserting errors into C program unless you insert debugging code –Example: Debugging statements can overrun stack Non-deterministic errors are really difficult to find –Example: Memory layout of kernel+user programs »depends on scheduling, which depends on timer/other things »Original UNIX had a bunch of non-deterministic errors –Example: Something which does interesting I/O »User typing of letters used to help generate secure keys

Lec /14/09Kubiatowicz CS162 ©UCB Fall 2009 Why allow cooperating threads? People cooperate; computers help/enhance people’s lives, so computers must cooperate –By analogy, the non-reproducibility/non-determinism of people is a notable problem for “carefully laid plans” Advantage 1: Share resources –One computer, many users –One bank balance, many ATMs »What if ATMs were only updated at night? –Embedded systems (robot control: coordinate arm & hand) Advantage 2: Speedup –Overlap I/O and computation »Many different file systems do read-ahead –Multiprocessors – chop up program into parallel pieces Advantage 3: Modularity –More important than you might think –Chop large problem up into simpler pieces »To compile, for instance, gcc calls cpp | cc1 | cc2 | as | ld »Makes system easier to extend

Lec /14/09Kubiatowicz CS162 ©UCB Fall 2009 High-level Example: Web Server Server must handle many requests Non-cooperating version: serverLoop() { con = AcceptCon(); ProcessFork(ServiceWebPage(),con); } What are some disadvantages of this technique?

Lec /14/09Kubiatowicz CS162 ©UCB Fall 2009 Threaded Web Server Now, use a single process Multithreaded (cooperating) version: serverLoop() { connection = AcceptCon(); ThreadFork(ServiceWebPage(),connection); } Looks almost the same, but has many advantages: –Can share file caches kept in memory, results of CGI scripts, other things –Threads are much cheaper to create than processes, so this has a lower per-request overhead Question: would a user-level (say one-to-many) thread package make sense here? –When one request blocks on disk, all block… What about Denial of Service attacks or digg / Slash-dot effects?

Lec /14/09Kubiatowicz CS162 ©UCB Fall 2009 Thread Pools Problem with previous version: Unbounded Threads –When web-site becomes too popular – throughput sinks Instead, allocate a bounded “pool” of worker threads, representing the maximum level of multiprogramming master() { allocThreads(worker,queue); while(TRUE) { con=AcceptCon(); Enqueue(queue,con); wakeUp(queue); } } worker(queue) { while(TRUE) { con=Dequeue(queue); if (con==null) sleepOn(queue); else ServiceWebPage(con); } } Master Thread Thread Pool queue

Lec /14/09Kubiatowicz CS162 ©UCB Fall 2009 Summary Interrupts: hardware mechanism for returning control to operating system –Used for important/high-priority events –Can force dispatcher to schedule a different thread (premptive multithreading) New Threads Created with ThreadFork() –Create initial TCB and stack to point at ThreadRoot() –ThreadRoot() calls thread code, then ThreadFinish() –ThreadFinish() wakes up waiting threads then prepares TCB/stack for distruction Threads can wait for other threads using ThreadJoin() Threads may be at user-level or kernel level Cooperating threads have many potential advantages –But: introduces non-reproducibility and non-determinism –Need to have Atomic operations