Click here to load reader

CS162 Operating Systems and Systems Programming Lecture 2 Synchronization January 26 th, 2011 Ion Stoica cs162

  • View
    216

  • Download
    0

Embed Size (px)

Text of CS162 Operating Systems and Systems Programming Lecture 2 Synchronization January 26 th, 2011 Ion...

  • CS162Operating Systems andSystems ProgrammingLecture 2

    SynchronizationJanuary 26th, 2011Ion Stoicahttp://inst.eecs.berkeley.edu/~cs162

    Lec 1.*1/19/10Ion Stoica CS162 UCB Spring 2011

    Execution Stack ExampleStack holds function arguments, return addressPermits recursive executionCrucial to modern languages

    addrX:addrY:addrU:addrV:addrZ:...

    ...

    ...

    ...

    Lec 1.*1/19/10Ion Stoica CS162 UCB Spring 2011

    Execution Stack ExampleStack holds function arguments, return addressPermits recursive executionCrucial to modern languages

    Stack GrowthA: tmp=1 ret=addrZaddrX:addrY:addrU:addrV:addrZ:...

    ...

    ...

    ...

    Lec 1.*1/19/10Ion Stoica CS162 UCB Spring 2011

    Execution Stack ExampleStack holds function arguments, return addressPermits recursive executionCrucial to modern languages

    Stack GrowthA: tmp=1 ret=addrZaddrX:addrY:addrU:addrV:addrZ:...

    ...

    ...

    ...

    Lec 1.*1/19/10Ion Stoica CS162 UCB Spring 2011

    Execution Stack ExampleStack holds function arguments, return addressPermits recursive executionCrucial to modern languages

    Stack GrowthA: tmp=1 ret=addrZB: ret=addrYaddrX:addrY:addrU:addrV:addrZ:...

    ...

    ...

    ...

    Lec 1.*1/19/10Ion Stoica CS162 UCB Spring 2011

    Execution Stack ExampleStack holds function arguments, return addressPermits recursive executionCrucial to modern languages

    Stack GrowthA: tmp=1 ret=addrZB: ret=addrYC: ret=addrUaddrX:addrY:addrU:addrV:addrZ:...

    ...

    ...

    ...

    Lec 1.*1/19/10Ion Stoica CS162 UCB Spring 2011

    Execution Stack ExampleStack holds function arguments, return addressPermits recursive executionCrucial to modern languages

    A: tmp=2 ret=addrVStack GrowthA: tmp=1 ret=addrZB: ret=addrYC: ret=addrUaddrX:addrY:addrU:addrV:addrZ:...

    ...

    ...

    ...

    Lec 1.*1/19/10Ion Stoica CS162 UCB Spring 2011

    Execution Stack ExampleA: tmp=2 ret=addrVStack GrowthA: tmp=1 ret=addrZB: ret=addrYC: ret=addrUaddrX:addrY:addrU:addrV:addrZ:...

    ...

    ...

    ...Output:

    Lec 1.*1/19/10Ion Stoica CS162 UCB Spring 2011

    Execution Stack ExampleA: tmp=2 ret=addrVStack GrowthA: tmp=1 ret=addrZB: ret=addrYC: ret=addrUaddrX:addrY:addrU:addrV:addrZ:...

    ...

    ...

    ...Output:2

    Lec 1.*1/19/10Ion Stoica CS162 UCB Spring 2011

    Execution Stack ExampleStack GrowthA: tmp=1 ret=addrZB: ret=addrYC: ret=addrUaddrX:addrY:addrU:addrV:addrZ:...

    ...

    ...

    ...Output:2

    Lec 1.*1/19/10Ion Stoica CS162 UCB Spring 2011

    Execution Stack ExampleStack GrowthA: tmp=1 ret=addrZB: ret=addrYaddrX:addrY:addrU:addrV:addrZ:...

    ...

    ...

    ...Output:2

    Lec 1.*1/19/10Ion Stoica CS162 UCB Spring 2011

    Execution Stack ExampleStack GrowthA: tmp=1 ret=addrZaddrX:addrY:addrU:addrV:addrZ:...

    ...

    ...

    ...Output:21

    Lec 1.*1/19/10Ion Stoica CS162 UCB Spring 2011

    Execution Stack ExampleaddrX:addrY:addrU:addrV:addrZ:...

    ...

    ...

    ...Output:21

    Lec 1.*1/19/10Ion Stoica CS162 UCB Spring 2011

    ClassificationReal operating systems have eitherOne or many address spacesOne or many threads per address spaceDid Windows 95/98/ME have real memory protection?No: Users could overwrite process tables / system DLLsMach, OS/2, Linux,Win 95?, Mac OS X,Win NT to XP, Solaris, HP-UXEmbedded systems (Geoworks, VxWorks, JavaOS,etc)JavaOS, Pilot(PC)Traditional UNIXMS/DOS, early Macintosh

    Lec 1.*1/19/10Ion Stoica CS162 UCB Spring 2011

    Goals for TodayThread DispatchingCooperating ThreadsConcurrency examplesNeed for synchronization

    Note: Some slides and/or pictures in the following areadapted from slides 2005 Silberschatz, Galvin, and Gagne. Many slides generated from lecture notes by Kubiatowicz.

    Lec 1.*1/19/10Ion Stoica CS162 UCB Spring 2011

    Single-Threaded ExampleImagine the following C program: main() { ComputePI(pi.txt); PrintClassList(clist.text);}

    What is the behavior here?Program would never print out class listWhy? ComputePI would never finish

    Lec 1.*1/19/10Ion Stoica CS162 UCB Spring 2011

    Use of ThreadsVersion of program with Threads: main() { CreateThread(ComputePI(pi.txt)); CreateThread(PrintClassList(clist.text));}

    What does CreateThread do?Start independent thread running given procedureWhat is the behavior here?Now, you would actually see the class listThis should behave as if there are two separate CPUs

    Lec 1.*1/19/10Ion Stoica CS162 UCB Spring 2011

    Memory Footprint of Two-Thread ExampleIf we stopped this program and examined it with a debugger, we would seeTwo sets of CPU registersTwo sets of Stacks

    Questions: How do we position stacks relative to each other?What maximum size should we choose for the stacks?What happens if threads violate this?How might you catch violations?

    Lec 1.*1/19/10Ion Stoica CS162 UCB Spring 2011

    Per Thread StateEach Thread has a Thread Control Block (TCB)Execution State: CPU registers, program counter, pointer to stackScheduling info: State, priority, CPU timeAccounting InfoVarious 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 memoryIn Array, or Linked List, or

    Lec 1.*1/19/10Ion Stoica CS162 UCB Spring 2011

    Lifecycle of a Thread (or Process)As a thread executes, it changes state:new: The thread is being createdready: The thread is waiting to runrunning: Instructions are being executedwaiting: Thread waiting for some event to occurterminated: The thread has finished executionActive threads are represented by their TCBsTCBs organized into queues based on their state

    Lec 1.*1/19/10Ion Stoica CS162 UCB Spring 2011

    Ready Queue And Various I/O Device QueuesThread not running TCB is in some scheduler queueSeparate queue for each device/signal/condition Each queue can have a different scheduler policy

    Lec 1.*1/19/10Ion Stoica CS162 UCB Spring 2011

    Dispatch LoopConceptually, the dispatching loop of the operating system looks as follows: Loop { RunThread(); ChooseNextThread(); SaveStateOfCPU(curTCB); LoadStateOfCPU(newTCB);}

    This is an infinite loopOne could argue that this is all that the OS does

    Lec 1.*1/19/10Ion Stoica CS162 UCB Spring 2011

    Running a threadConsider first portion: RunThread()

    How do I run a thread?Load its state (registers, PC, stack pointer) into CPULoad environment (virtual memory space, etc)Jump to the PC

    How does the dispatcher get control back?Internal events: thread returns control voluntarilyExternal events: thread gets preempted

    Lec 1.*1/19/10Ion Stoica CS162 UCB Spring 2011

    Review: Yielding through Internal EventsBlocking on I/OThe act of requesting I/O implicitly yields the CPUWaiting on a signal from other threadThread asks to wait and thus yields the CPUThread executes a yield()Thread volunteers to give up CPUcomputePI() { while(TRUE) { ComputeNextDigit(); yield(); } }Note that yield() must be called by programmer frequently enough!

    Lec 1.*1/19/10Ion Stoica CS162 UCB Spring 2011

    Review: Stack for Yielding ThreadHow do we run a new thread?run_new_thread() { newThread = PickNewThread(); switch(curThread, newThread); ThreadHouseKeeping(); /* deallocates finished threads */}Finished thread not killed right away. Why?Move them in exit stateThreadHouseKeeping() deallocates finished threadsyieldComputePI

    Lec 1.*1/19/10Ion Stoica CS162 UCB Spring 2011

    Review: Stack for Yielding ThreadHow do we run a new thread?run_new_thread() { newThread = PickNewThread(); switch(curThread, newThread); ThreadHouseKeeping(); /* deallocates finished threads */}How does dispatcher switch to a new thread?Save anything next thread may trash: PC, regs, stackMaintain isolation for each threadyieldComputePI

    Lec 1.*1/19/10Ion Stoica CS162 UCB Spring 2011

    Review: Two Thread Yield ExampleConsider the following code blocks: proc A() { B();}proc B() { while(TRUE) { yield(); }}Suppose we have 2 threads:Threads S and T

    Lec 1.*1/19/10Ion Stoica CS162 UCB Spring 2011

    Detour: Interrupt ControllerInterrupts invoked with interrupt lines from devicesInterrupt controller chooses interrupt request to honorMask enables/disables interruptsPriority encoder picks highest enabled interrupt Software Interrupt Set/Cleared by SoftwareInterrupt identity specified with ID lineCPU can disable all interrupts with internal flagNon-maskable interrupt line (NMI) cant be disabledNetworkIntIDInterruptInterrupt MaskControlSoftwareInterruptCPUPriority EncoderTimer

    Lec 1.*1/19/10Ion Stoica CS162 UCB Spring 2011

    Review: Preemptive MultithreadingUse 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 schedulingSolves problem of user who doesnt insert yield();

    Lec 1.*1/19/10Ion Stoica CS162 UCB Spring 2011

    Project SignupProject Signup: Watch Group/Section Signup Link4-5 members to a groupEveryone in group must be able to actually attend same sectionThe sections assigned to you by Telebears are temporary!Only submit once per group!Everyone in group must have logged into their cs162-xx accounts once before you register the groupMake sure that you select at least 2 potential sectionsHard deadline: due Friday (1/28) by 11:59pmSections:Watch for section assignments next Monday/TuesdayAttend new sections next week

    SectionTimeLocationTA101Th 10:00A-11:00A 3105 EtcheverryJorge Ortiz102Th 11:00A-12:00P 4 Evans104Th 1:00P-2:00P 85 EvansStephen Dawson-Haggerty105Th 2:00P-3:00P B56 Hildebrand103Th 3:00P-4:00P 4 Ev