SlideShare ist ein Scribd-Unternehmen logo
1 von 42
Downloaden Sie, um offline zu lesen
Processes and Threads
    Implementation




                        1
Learning Outcomes
• An understanding of the typical implementation
  strategies of processes and threads
  – Including an appreciation of the trade-offs between
    the implementation approaches
     • Kernel-threads versus user-level threads
• A detailed understanding of “context switching”




                                                          2
Summary: The Process Model




• Multiprogramming of four programs
• Conceptual model of 4 independent, sequential
  processes (with a single thread each)
• Only one program active at any instant          3
Processes
User Mode




        Process A     Process B   Process C




                      Scheduler
Kernel Mode
Processes
• User-mode
   – Processes (programs) scheduled by the kernel
   – Isolated from each other
   – No concurrency issues between each other
• System-calls transition into and return from the kernel
• Kernel-mode
   – Nearly all activities still associated with a process
   – Kernel memory shared between all processes
   – Concurrency issues exist between processes concurrently
     executing in a system call



                                                               5
Threads
              The Thread Model




(a) Three processes each with one thread
(b) One process with three threads
                                           6
The Thread Model




• Items shared by all threads in a process
• Items private to each thread
                                             7
The Thread Model




Each thread has its own stack
                                8
Implementing Threads in User
           Space




    A user-level threads package
                                   9
User-level Threads
User Mode




       Scheduler     Scheduler   Scheduler




        Process A   Process B    Process C




                    Scheduler
Kernel Mode
User-level Threads
• Implementation at user-level
  – User-level Thread Control Block (TCB), ready
    queue, blocked queue, and dispatcher
  – Kernel has no knowledge of the threads (it
    only sees a single process)
  – If a thread blocks waiting for a resource held
    by another thread, its state is saved and the
    dispatcher switches to another ready thread
  – Thread management (create, exit, yield, wait)
    are implemented in a runtime support library
                                               11
User-Level Threads
• Pros
  – Thread management and switching at user level is much faster
    than doing it in kernel level
      • No need to trap (take syscall exception) into kernel and back to
        switch
  – Dispatcher algorithm can be tuned to the application
      • E.g. use priorities
  – Can be implemented on any OS (thread or non-thread aware)
  – Can easily support massive numbers of threads on a per-
    application basis
      • Use normal application virtual memory
      • Kernel memory more constrained. Difficult to efficiently support
        wildly differing numbers of threads for different applications.



                                                                           12
User-level Threads
• Cons
  – Threads have to yield() manually (no timer
    interrupt delivery to user-level)
     • Co-operative multithreading
         – A single poorly design/implemented thread can
           monopolise the available CPU time
     • There are work-arounds (e.g. a timer signal per
       second to enable pre-emptive multithreading), they
       are course grain and a kludge.
  – Does not take advantage of multiple CPUs (in
    reality, we still have a single threaded process
    as far as the kernel is concerned)
                                                           13
User-Level Threads
• Cons
  – If a thread makes a blocking system call (or takes a page fault),
    the process (and all the internal threads) blocks
      • Can’t overlap I/O with computation
      • Can use wrappers as a work around
          – Example: wrap the read() call
          – Use select() to test if read system call would block
              » select() then read()
              » Only call read() if it won’t block
              » Otherwise schedule another thread
          – Wrapper requires 2 system calls instead of one
              » Wrappers are needed for environments doing lots of blocking
                system calls – exactly when efficiency matters!




                                                                              14
15
Implementing Threads in the Kernel




    A threads package managed by the kernel
                                              16
Kernel-Level Threads
User Mode




        Process A   Process B   Process C




                    Scheduler
Kernel Mode
Kernel Threads
• Threads are implemented in the kernel
  – TCBs are stored in the kernel
    • A subset of information in a traditional PCB
       – The subset related to execution context
    • TCBs have a PCB associated with them
       – Resources associated with the group of threads (the
         process)
  – Thread management calls are implemented
    as system calls
    • E.g. create, wait, exit
                                                               18
Kernel Threads
• Cons
  – Thread creation and destruction, and blocking
    and unblocking threads requires kernel entry
    and exit.
    • More expensive than user-level equivalent
• Pros
  – Preemptive multithreading
  – Parallelism
    • Can overlap blocking I/O with computation
    • Can take advantage of a multiprocessor
                                                  19
Multiprogramming Implementation




Skeleton of what lowest level of OS does when an
   interrupt occurs – a thread/context switch
                                            20
Thread Switch
• A switch between threads can happen any time
  the OS is invoked
  – On a system call
     • Mandatory if system call blocks or on exit();
  – On an exception
     • Mandatory if offender is killed
  – On an interrupt
     • Triggering a dispatch is the main purpose of the timer
       interrupt
A thread switch can happen between any two
  instructions
Note instructions do not equal program statements
                                                                21
Context Switch
• Thread switch must be transparent for threads
  – When dispatched again, thread should not notice that
    something else was running in the meantime (except
    for elapsed time)
⇒OS must save all state that affects the thread
• This state is called the thread context
• Switching between threads consequently results
  in a context switch.


                                                     22
Thread a                    Thread b         Simplified
       thread_switch(a,b)         }
                                              Explicit
       {
                                           Thread Switch
       }                          thread_switch(b,a)
                                  {




       thread_switch(a,b)         }
       {




                                                       23
Kernel-Level Threads
User Mode




        Process A   Process B   Process C




                    Scheduler
Kernel Mode
Example Context Switch
• Running in user mode, SP points to user-
  level stack (not shown on slide)

Representation of
  Kernel Stack                 SP
   (Memory)




                                         25
Example Context Switch
• Take an exception, syscall, or interrupt,
  and we switch to the kernel stack


                                  SP




                                              26
Example Context Switch
• We push a trapframe on the stack
  – Also called exception frame, user-level context….
  – Includes the user-level PC and SP

                                         SP



                                            trapframe


                                                        27
Example Context Switch
• Call ‘C’ code to process syscall, exception,
  or interrupt
  – Results in a ‘C’ activation stack building up

                                           SP



                    ‘C’ activation stack    trapframe


                                                        28
Example Context Switch
• The kernel decides to perform a context switch
  – It chooses a target thread (or process)
  – It pushes remaining kernel context onto the stack

                                               SP



           Kernel State ‘C’ activation stack    trapframe


                                                            29
Example Context Switch
   • Any other existing thread must
       – be in kernel mode (on a uni processor),
       – and have a similar stack layout to the stack we are
         currently using

Kernel stacks of other                                 SP
 threads/processes



                   Kernel State ‘C’ activation stack    trapframe
                   Kernel State ‘C’ activation stack    trapframe
                   Kernel State ‘C’ activation stack    trapframe
                                                                    30
Example Context Switch
• We save the current SP in the PCB (or TCB),
  and load the SP of the target thread.
  – Thus we have switched contexts

                                              SP



          Kernel State ‘C’ activation stack    trapframe
          Kernel State ‘C’ activation stack    trapframe
          Kernel State ‘C’ activation stack    trapframe
                                                           31
Example Context Switch
• Load the target thread’s previous context,
  and return to C


                                             SP



         Kernel State ‘C’ activation stack    trapframe
                     ‘C’ activation stack     trapframe
         Kernel State ‘C’ activation stack    trapframe
                                                          32
Example Context Switch
• The C continues and (in this example)
  returns to user mode.


                                             SP



         Kernel State ‘C’ activation stack    trapframe
                                              trapframe
         Kernel State ‘C’ activation stack    trapframe
                                                          33
Example Context Switch
• The user-level context is restored



                                              SP



          Kernel State ‘C’ activation stack    trapframe


          Kernel State ‘C’ activation stack    trapframe
                                                           34
Example Context Switch
• The user-level SP is restored



                                             SP



         Kernel State ‘C’ activation stack    trapframe


         Kernel State ‘C’ activation stack    trapframe
                                                          35
The Interesting Part of a Thread
             Switch
• What does the “push kernel state” part
  do???


                                             SP



         Kernel State ‘C’ activation stack    trapframe


         Kernel State ‘C’ activation stack    trapframe
                                                          36
Simplified OS/161 thread_switch
static
void
thread_switch(threadstate_t newstate, struct wchan *wc)
{
struct thread *cur, *next;

cur = curthread;
do {
   next = threadlist_remhead(&curcpu->c_runqueue);
   if (next == NULL) {
         cpu_idle();
   }
} while (next == NULL);

/* do the switch (in assembler in switch.S) */
switchframe_switch(&cur->t_context, &next->t_context);
                                                            Lots of code
                                                          removed – only
}
                                                           basics of pick
                                                          next thread and
                                                            run it remain
                                                                      37
OS/161 switchframe_switch
switchframe_switch:
 /*
  * a0 contains the address of the switchframe pointer in the old thread.
  * a1 contains the address of the switchframe pointer in the new thread.
  *
  * The switchframe pointer is really the stack pointer. The other
  * registers get saved on the stack, namely:
  *
  *    s0-s6, s8
  *    gp, ra
  *
  * The order must match <mips/switchframe.h>.
  *
  * Note that while we'd ordinarily need to save s7 too, because we
  * use it to hold curthread saving it would interfere with the way
  * curthread is managed by thread.c. So we'll just let thread.c
  * manage it.
  */
                                                                            38
OS/161 switchframe_switch
/* Allocate stack space for saving 10 registers. 10*4 = 40 */
addi sp, sp, -40

/* Save the registers */                                 Save the registers
sw ra, 36(sp)
sw gp, 32(sp)
                                                            that the ‘C’
sw s8, 28(sp)                                            procedure calling
sw s6, 24(sp)
sw s5, 20(sp)
                                                            convention
sw s4, 16(sp)                                                 expects
sw s3, 12(sp)                                                preserved
sw s2, 8(sp)
sw s1, 4(sp)
sw s0, 0(sp)

/* Store the old stack pointer in the old thread */
sw sp, 0(a0)


                                                                              39
OS/161 switchframe_switch
/* Get the new stack pointer from the new thread */
lw sp, 0(a1)
nop        /* delay slot for load */

/* Now, restore the registers */
lw s0, 0(sp)
lw s1, 4(sp)
lw s2, 8(sp)
lw s3, 12(sp)
lw s4, 16(sp)
lw s5, 20(sp)
lw s6, 24(sp)
lw s8, 28(sp)
lw gp, 32(sp)
lw ra, 36(sp)
nop            /* delay slot for load */



                                                      40
OS/161 switchframe_switch
/* and return. */
j ra
addi sp, sp, 40     /* in delay slot */




                                          41
Thread a                         Thread b
                                                  Revisiting
       switchframe_switch(a,b)
       {
                                       }        Thread Switch

            }                          switchframe_switch(b,a)
                                       {




   switchframe_switch(a,b)             }
   {




                                                                 42

Weitere ähnliche Inhalte

Was ist angesagt?

Superscalar & superpipeline processor
Superscalar & superpipeline processorSuperscalar & superpipeline processor
Superscalar & superpipeline processorMuhammad Ishaq
 
Scheduler Activations - Effective Kernel Support for the User-Level Managemen...
Scheduler Activations - Effective Kernel Support for the User-Level Managemen...Scheduler Activations - Effective Kernel Support for the User-Level Managemen...
Scheduler Activations - Effective Kernel Support for the User-Level Managemen...Kasun Gajasinghe
 
Advanced processor principles
Advanced processor principlesAdvanced processor principles
Advanced processor principlesDhaval Bagal
 
Process, Threads, Symmetric Multiprocessing and Microkernels in Operating System
Process, Threads, Symmetric Multiprocessing and Microkernels in Operating SystemProcess, Threads, Symmetric Multiprocessing and Microkernels in Operating System
Process, Threads, Symmetric Multiprocessing and Microkernels in Operating SystemLieYah Daliah
 
Hardware multithreading
Hardware multithreadingHardware multithreading
Hardware multithreadingFraboni Ec
 
Superscalar Architecture_AIUB
Superscalar Architecture_AIUBSuperscalar Architecture_AIUB
Superscalar Architecture_AIUBNusrat Mary
 
Lect.10.arm soc.4 neon
Lect.10.arm soc.4 neonLect.10.arm soc.4 neon
Lect.10.arm soc.4 neonsean chen
 
Chip Multithreading Systems Need a New Operating System Scheduler
Chip Multithreading Systems Need a New Operating System Scheduler Chip Multithreading Systems Need a New Operating System Scheduler
Chip Multithreading Systems Need a New Operating System Scheduler Sarwan ali
 
Fast switching of threads between cores - Advanced Operating Systems
Fast switching of threads between cores - Advanced Operating SystemsFast switching of threads between cores - Advanced Operating Systems
Fast switching of threads between cores - Advanced Operating SystemsRuhaim Izmeth
 
[Harvard CS264] 11b - Analysis-Driven Performance Optimization with CUDA (Cli...
[Harvard CS264] 11b - Analysis-Driven Performance Optimization with CUDA (Cli...[Harvard CS264] 11b - Analysis-Driven Performance Optimization with CUDA (Cli...
[Harvard CS264] 11b - Analysis-Driven Performance Optimization with CUDA (Cli...npinto
 
[Harvard CS264] 11a - Programming the Memory Hierarchy with Sequoia (Mike Bau...
[Harvard CS264] 11a - Programming the Memory Hierarchy with Sequoia (Mike Bau...[Harvard CS264] 11a - Programming the Memory Hierarchy with Sequoia (Mike Bau...
[Harvard CS264] 11a - Programming the Memory Hierarchy with Sequoia (Mike Bau...npinto
 
Analysis of interrupt latencies in a real-time kernel
Analysis of interrupt latencies in a real-time kernelAnalysis of interrupt latencies in a real-time kernel
Analysis of interrupt latencies in a real-time kernelGabriele Modena
 
Operating Systems 1 (10/12) - Scheduling
Operating Systems 1 (10/12) - SchedulingOperating Systems 1 (10/12) - Scheduling
Operating Systems 1 (10/12) - SchedulingPeter Tröger
 
Multithreading: Exploiting Thread-Level Parallelism to Improve Uniprocessor ...
Multithreading: Exploiting Thread-Level  Parallelism to Improve Uniprocessor ...Multithreading: Exploiting Thread-Level  Parallelism to Improve Uniprocessor ...
Multithreading: Exploiting Thread-Level Parallelism to Improve Uniprocessor ...Ahmed kasim
 
Advanced computer architecture lesson 5 and 6
Advanced computer architecture lesson 5 and 6Advanced computer architecture lesson 5 and 6
Advanced computer architecture lesson 5 and 6Ismail Mukiibi
 

Was ist angesagt? (20)

Superscalar & superpipeline processor
Superscalar & superpipeline processorSuperscalar & superpipeline processor
Superscalar & superpipeline processor
 
Scheduler Activations - Effective Kernel Support for the User-Level Managemen...
Scheduler Activations - Effective Kernel Support for the User-Level Managemen...Scheduler Activations - Effective Kernel Support for the User-Level Managemen...
Scheduler Activations - Effective Kernel Support for the User-Level Managemen...
 
Advanced processor principles
Advanced processor principlesAdvanced processor principles
Advanced processor principles
 
Process, Threads, Symmetric Multiprocessing and Microkernels in Operating System
Process, Threads, Symmetric Multiprocessing and Microkernels in Operating SystemProcess, Threads, Symmetric Multiprocessing and Microkernels in Operating System
Process, Threads, Symmetric Multiprocessing and Microkernels in Operating System
 
Hardware multithreading
Hardware multithreadingHardware multithreading
Hardware multithreading
 
Multicore Processors
Multicore ProcessorsMulticore Processors
Multicore Processors
 
VLIW Processors
VLIW ProcessorsVLIW Processors
VLIW Processors
 
Superscalar Architecture_AIUB
Superscalar Architecture_AIUBSuperscalar Architecture_AIUB
Superscalar Architecture_AIUB
 
Lect.10.arm soc.4 neon
Lect.10.arm soc.4 neonLect.10.arm soc.4 neon
Lect.10.arm soc.4 neon
 
Chip Multithreading Systems Need a New Operating System Scheduler
Chip Multithreading Systems Need a New Operating System Scheduler Chip Multithreading Systems Need a New Operating System Scheduler
Chip Multithreading Systems Need a New Operating System Scheduler
 
Fast switching of threads between cores - Advanced Operating Systems
Fast switching of threads between cores - Advanced Operating SystemsFast switching of threads between cores - Advanced Operating Systems
Fast switching of threads between cores - Advanced Operating Systems
 
3 process management
3 process management3 process management
3 process management
 
[Harvard CS264] 11b - Analysis-Driven Performance Optimization with CUDA (Cli...
[Harvard CS264] 11b - Analysis-Driven Performance Optimization with CUDA (Cli...[Harvard CS264] 11b - Analysis-Driven Performance Optimization with CUDA (Cli...
[Harvard CS264] 11b - Analysis-Driven Performance Optimization with CUDA (Cli...
 
[Harvard CS264] 11a - Programming the Memory Hierarchy with Sequoia (Mike Bau...
[Harvard CS264] 11a - Programming the Memory Hierarchy with Sequoia (Mike Bau...[Harvard CS264] 11a - Programming the Memory Hierarchy with Sequoia (Mike Bau...
[Harvard CS264] 11a - Programming the Memory Hierarchy with Sequoia (Mike Bau...
 
Analysis of interrupt latencies in a real-time kernel
Analysis of interrupt latencies in a real-time kernelAnalysis of interrupt latencies in a real-time kernel
Analysis of interrupt latencies in a real-time kernel
 
Cpu Caches
Cpu CachesCpu Caches
Cpu Caches
 
Operating Systems 1 (10/12) - Scheduling
Operating Systems 1 (10/12) - SchedulingOperating Systems 1 (10/12) - Scheduling
Operating Systems 1 (10/12) - Scheduling
 
Multithreading: Exploiting Thread-Level Parallelism to Improve Uniprocessor ...
Multithreading: Exploiting Thread-Level  Parallelism to Improve Uniprocessor ...Multithreading: Exploiting Thread-Level  Parallelism to Improve Uniprocessor ...
Multithreading: Exploiting Thread-Level Parallelism to Improve Uniprocessor ...
 
Advanced computer architecture lesson 5 and 6
Advanced computer architecture lesson 5 and 6Advanced computer architecture lesson 5 and 6
Advanced computer architecture lesson 5 and 6
 
Parallel processing
Parallel processingParallel processing
Parallel processing
 

Andere mochten auch

Supply, Demand, and Government Policies
Supply, Demand, and Government PoliciesSupply, Demand, and Government Policies
Supply, Demand, and Government PoliciesChris Thomas
 
The Law of Supply and Demand, and Government Intervention
The Law of Supply and Demand, and Government InterventionThe Law of Supply and Demand, and Government Intervention
The Law of Supply and Demand, and Government InterventionJeremy Paul Gecolea
 
Ch06 Supply Demand And Government Policies
Ch06 Supply Demand And Government PoliciesCh06 Supply Demand And Government Policies
Ch06 Supply Demand And Government PoliciesKevin A
 
supply,demand, and government policies
supply,demand, and government policiessupply,demand, and government policies
supply,demand, and government policiesitmamul akwan
 
Supply, Demand & Government Policies
Supply, Demand & Government PoliciesSupply, Demand & Government Policies
Supply, Demand & Government PoliciesCASE
 
Marketing kisi2-2014
Marketing kisi2-2014Marketing kisi2-2014
Marketing kisi2-2014Smp Al-Hadi
 
সৃজনশীল প্রশ্ন, শিক্ষক ও শ্রেণি কার্যক্রম
সৃজনশীল প্রশ্ন, শিক্ষক ও শ্রেণি কার্যক্রমসৃজনশীল প্রশ্ন, শিক্ষক ও শ্রেণি কার্যক্রম
সৃজনশীল প্রশ্ন, শিক্ষক ও শ্রেণি কার্যক্রমAbul Bashar
 
library class power point
library class power pointlibrary class power point
library class power pointdparkin
 
コドモノガタリ イクメン調査120328
コドモノガタリ イクメン調査120328コドモノガタリ イクメン調査120328
コドモノガタリ イクメン調査120328Takaho Maeda
 
Savico residence
Savico residenceSavico residence
Savico residencetranduyen76
 
LibreOffice ヘルプを翻訳してみよう
LibreOffice ヘルプを翻訳してみようLibreOffice ヘルプを翻訳してみよう
LibreOffice ヘルプを翻訳してみようKazumi Ohhashi
 
使用Rpm&yum进行基础软件管理
使用Rpm&yum进行基础软件管理使用Rpm&yum进行基础软件管理
使用Rpm&yum进行基础软件管理Jason Zheng
 
Cpa network presentation_unisender_conf_prefinal
Cpa network presentation_unisender_conf_prefinalCpa network presentation_unisender_conf_prefinal
Cpa network presentation_unisender_conf_prefinalKira Zhestkova
 
Presentation to News:Rewired 2011
Presentation to News:Rewired 2011Presentation to News:Rewired 2011
Presentation to News:Rewired 2011onthewight
 
математик3а
математик3аматематик3а
математик3аtsatsraletka
 
Drawing human bodies
Drawing human bodiesDrawing human bodies
Drawing human bodieskyop
 
Yarmouth in the 20th Century
Yarmouth in the 20th CenturyYarmouth in the 20th Century
Yarmouth in the 20th Centuryonthewight
 
Presentation tecniacustica 2013
Presentation tecniacustica 2013Presentation tecniacustica 2013
Presentation tecniacustica 2013Alvaro Barbosa
 

Andere mochten auch (20)

Supply, Demand, and Government Policies
Supply, Demand, and Government PoliciesSupply, Demand, and Government Policies
Supply, Demand, and Government Policies
 
The Law of Supply and Demand, and Government Intervention
The Law of Supply and Demand, and Government InterventionThe Law of Supply and Demand, and Government Intervention
The Law of Supply and Demand, and Government Intervention
 
Ch06 Supply Demand And Government Policies
Ch06 Supply Demand And Government PoliciesCh06 Supply Demand And Government Policies
Ch06 Supply Demand And Government Policies
 
supply,demand, and government policies
supply,demand, and government policiessupply,demand, and government policies
supply,demand, and government policies
 
Supply, Demand & Government Policies
Supply, Demand & Government PoliciesSupply, Demand & Government Policies
Supply, Demand & Government Policies
 
Marketing kisi2-2014
Marketing kisi2-2014Marketing kisi2-2014
Marketing kisi2-2014
 
সৃজনশীল প্রশ্ন, শিক্ষক ও শ্রেণি কার্যক্রম
সৃজনশীল প্রশ্ন, শিক্ষক ও শ্রেণি কার্যক্রমসৃজনশীল প্রশ্ন, শিক্ষক ও শ্রেণি কার্যক্রম
সৃজনশীল প্রশ্ন, শিক্ষক ও শ্রেণি কার্যক্রম
 
library class power point
library class power pointlibrary class power point
library class power point
 
Moianès-ILOQUID
Moianès-ILOQUIDMoianès-ILOQUID
Moianès-ILOQUID
 
コドモノガタリ イクメン調査120328
コドモノガタリ イクメン調査120328コドモノガタリ イクメン調査120328
コドモノガタリ イクメン調査120328
 
Savico residence
Savico residenceSavico residence
Savico residence
 
LibreOffice ヘルプを翻訳してみよう
LibreOffice ヘルプを翻訳してみようLibreOffice ヘルプを翻訳してみよう
LibreOffice ヘルプを翻訳してみよう
 
使用Rpm&yum进行基础软件管理
使用Rpm&yum进行基础软件管理使用Rpm&yum进行基础软件管理
使用Rpm&yum进行基础软件管理
 
Cpa network presentation_unisender_conf_prefinal
Cpa network presentation_unisender_conf_prefinalCpa network presentation_unisender_conf_prefinal
Cpa network presentation_unisender_conf_prefinal
 
Insiderdigital 2013
Insiderdigital 2013Insiderdigital 2013
Insiderdigital 2013
 
Presentation to News:Rewired 2011
Presentation to News:Rewired 2011Presentation to News:Rewired 2011
Presentation to News:Rewired 2011
 
математик3а
математик3аматематик3а
математик3а
 
Drawing human bodies
Drawing human bodiesDrawing human bodies
Drawing human bodies
 
Yarmouth in the 20th Century
Yarmouth in the 20th CenturyYarmouth in the 20th Century
Yarmouth in the 20th Century
 
Presentation tecniacustica 2013
Presentation tecniacustica 2013Presentation tecniacustica 2013
Presentation tecniacustica 2013
 

Ähnlich wie Lect06

Ähnlich wie Lect06 (20)

OS Thr schd.ppt
OS Thr schd.pptOS Thr schd.ppt
OS Thr schd.ppt
 
Thread
ThreadThread
Thread
 
Thread
ThreadThread
Thread
 
chapter4-processes nd processors in DS.ppt
chapter4-processes nd processors in DS.pptchapter4-processes nd processors in DS.ppt
chapter4-processes nd processors in DS.ppt
 
Synchronization linux
Synchronization linuxSynchronization linux
Synchronization linux
 
Multithreading models
Multithreading modelsMultithreading models
Multithreading models
 
Multithreaded Programming Part- III.pdf
Multithreaded Programming Part- III.pdfMultithreaded Programming Part- III.pdf
Multithreaded Programming Part- III.pdf
 
Modern Java Concurrency (Devoxx Nov/2011)
Modern Java Concurrency (Devoxx Nov/2011)Modern Java Concurrency (Devoxx Nov/2011)
Modern Java Concurrency (Devoxx Nov/2011)
 
Threads
ThreadsThreads
Threads
 
CUG2011 Introduction to GPU Computing
CUG2011 Introduction to GPU ComputingCUG2011 Introduction to GPU Computing
CUG2011 Introduction to GPU Computing
 
4 threads
4 threads4 threads
4 threads
 
Ch04 threads
Ch04 threadsCh04 threads
Ch04 threads
 
Multithreaded processors ppt
Multithreaded processors pptMultithreaded processors ppt
Multithreaded processors ppt
 
Thread
ThreadThread
Thread
 
1 Multithreading basics.pptx
1 Multithreading basics.pptx1 Multithreading basics.pptx
1 Multithreading basics.pptx
 
Os
OsOs
Os
 
High Performance Computer Architecture
High Performance Computer ArchitectureHigh Performance Computer Architecture
High Performance Computer Architecture
 
Concept of thread
Concept of threadConcept of thread
Concept of thread
 
Ch4 threads
Ch4   threadsCh4   threads
Ch4 threads
 
Hardware Multithreading.pdf
Hardware Multithreading.pdfHardware Multithreading.pdf
Hardware Multithreading.pdf
 

Mehr von Vin Voro

Tele3113 tut6
Tele3113 tut6Tele3113 tut6
Tele3113 tut6Vin Voro
 
Tele3113 tut5
Tele3113 tut5Tele3113 tut5
Tele3113 tut5Vin Voro
 
Tele3113 tut4
Tele3113 tut4Tele3113 tut4
Tele3113 tut4Vin Voro
 
Tele3113 tut1
Tele3113 tut1Tele3113 tut1
Tele3113 tut1Vin Voro
 
Tele3113 tut3
Tele3113 tut3Tele3113 tut3
Tele3113 tut3Vin Voro
 
Tele3113 tut2
Tele3113 tut2Tele3113 tut2
Tele3113 tut2Vin Voro
 
Tele3113 wk11tue
Tele3113 wk11tueTele3113 wk11tue
Tele3113 wk11tueVin Voro
 
Tele3113 wk10wed
Tele3113 wk10wedTele3113 wk10wed
Tele3113 wk10wedVin Voro
 
Tele3113 wk10tue
Tele3113 wk10tueTele3113 wk10tue
Tele3113 wk10tueVin Voro
 
Tele3113 wk11wed
Tele3113 wk11wedTele3113 wk11wed
Tele3113 wk11wedVin Voro
 
Tele3113 wk7wed
Tele3113 wk7wedTele3113 wk7wed
Tele3113 wk7wedVin Voro
 
Tele3113 wk9tue
Tele3113 wk9tueTele3113 wk9tue
Tele3113 wk9tueVin Voro
 
Tele3113 wk8wed
Tele3113 wk8wedTele3113 wk8wed
Tele3113 wk8wedVin Voro
 
Tele3113 wk9wed
Tele3113 wk9wedTele3113 wk9wed
Tele3113 wk9wedVin Voro
 
Tele3113 wk7wed
Tele3113 wk7wedTele3113 wk7wed
Tele3113 wk7wedVin Voro
 
Tele3113 wk7wed
Tele3113 wk7wedTele3113 wk7wed
Tele3113 wk7wedVin Voro
 
Tele3113 wk7tue
Tele3113 wk7tueTele3113 wk7tue
Tele3113 wk7tueVin Voro
 
Tele3113 wk6wed
Tele3113 wk6wedTele3113 wk6wed
Tele3113 wk6wedVin Voro
 
Tele3113 wk6tue
Tele3113 wk6tueTele3113 wk6tue
Tele3113 wk6tueVin Voro
 
Tele3113 wk5tue
Tele3113 wk5tueTele3113 wk5tue
Tele3113 wk5tueVin Voro
 

Mehr von Vin Voro (20)

Tele3113 tut6
Tele3113 tut6Tele3113 tut6
Tele3113 tut6
 
Tele3113 tut5
Tele3113 tut5Tele3113 tut5
Tele3113 tut5
 
Tele3113 tut4
Tele3113 tut4Tele3113 tut4
Tele3113 tut4
 
Tele3113 tut1
Tele3113 tut1Tele3113 tut1
Tele3113 tut1
 
Tele3113 tut3
Tele3113 tut3Tele3113 tut3
Tele3113 tut3
 
Tele3113 tut2
Tele3113 tut2Tele3113 tut2
Tele3113 tut2
 
Tele3113 wk11tue
Tele3113 wk11tueTele3113 wk11tue
Tele3113 wk11tue
 
Tele3113 wk10wed
Tele3113 wk10wedTele3113 wk10wed
Tele3113 wk10wed
 
Tele3113 wk10tue
Tele3113 wk10tueTele3113 wk10tue
Tele3113 wk10tue
 
Tele3113 wk11wed
Tele3113 wk11wedTele3113 wk11wed
Tele3113 wk11wed
 
Tele3113 wk7wed
Tele3113 wk7wedTele3113 wk7wed
Tele3113 wk7wed
 
Tele3113 wk9tue
Tele3113 wk9tueTele3113 wk9tue
Tele3113 wk9tue
 
Tele3113 wk8wed
Tele3113 wk8wedTele3113 wk8wed
Tele3113 wk8wed
 
Tele3113 wk9wed
Tele3113 wk9wedTele3113 wk9wed
Tele3113 wk9wed
 
Tele3113 wk7wed
Tele3113 wk7wedTele3113 wk7wed
Tele3113 wk7wed
 
Tele3113 wk7wed
Tele3113 wk7wedTele3113 wk7wed
Tele3113 wk7wed
 
Tele3113 wk7tue
Tele3113 wk7tueTele3113 wk7tue
Tele3113 wk7tue
 
Tele3113 wk6wed
Tele3113 wk6wedTele3113 wk6wed
Tele3113 wk6wed
 
Tele3113 wk6tue
Tele3113 wk6tueTele3113 wk6tue
Tele3113 wk6tue
 
Tele3113 wk5tue
Tele3113 wk5tueTele3113 wk5tue
Tele3113 wk5tue
 

Kürzlich hochgeladen

THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 

Kürzlich hochgeladen (20)

TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 

Lect06

  • 1. Processes and Threads Implementation 1
  • 2. Learning Outcomes • An understanding of the typical implementation strategies of processes and threads – Including an appreciation of the trade-offs between the implementation approaches • Kernel-threads versus user-level threads • A detailed understanding of “context switching” 2
  • 3. Summary: The Process Model • Multiprogramming of four programs • Conceptual model of 4 independent, sequential processes (with a single thread each) • Only one program active at any instant 3
  • 4. Processes User Mode Process A Process B Process C Scheduler Kernel Mode
  • 5. Processes • User-mode – Processes (programs) scheduled by the kernel – Isolated from each other – No concurrency issues between each other • System-calls transition into and return from the kernel • Kernel-mode – Nearly all activities still associated with a process – Kernel memory shared between all processes – Concurrency issues exist between processes concurrently executing in a system call 5
  • 6. Threads The Thread Model (a) Three processes each with one thread (b) One process with three threads 6
  • 7. The Thread Model • Items shared by all threads in a process • Items private to each thread 7
  • 8. The Thread Model Each thread has its own stack 8
  • 9. Implementing Threads in User Space A user-level threads package 9
  • 10. User-level Threads User Mode Scheduler Scheduler Scheduler Process A Process B Process C Scheduler Kernel Mode
  • 11. User-level Threads • Implementation at user-level – User-level Thread Control Block (TCB), ready queue, blocked queue, and dispatcher – Kernel has no knowledge of the threads (it only sees a single process) – If a thread blocks waiting for a resource held by another thread, its state is saved and the dispatcher switches to another ready thread – Thread management (create, exit, yield, wait) are implemented in a runtime support library 11
  • 12. User-Level Threads • Pros – Thread management and switching at user level is much faster than doing it in kernel level • No need to trap (take syscall exception) into kernel and back to switch – Dispatcher algorithm can be tuned to the application • E.g. use priorities – Can be implemented on any OS (thread or non-thread aware) – Can easily support massive numbers of threads on a per- application basis • Use normal application virtual memory • Kernel memory more constrained. Difficult to efficiently support wildly differing numbers of threads for different applications. 12
  • 13. User-level Threads • Cons – Threads have to yield() manually (no timer interrupt delivery to user-level) • Co-operative multithreading – A single poorly design/implemented thread can monopolise the available CPU time • There are work-arounds (e.g. a timer signal per second to enable pre-emptive multithreading), they are course grain and a kludge. – Does not take advantage of multiple CPUs (in reality, we still have a single threaded process as far as the kernel is concerned) 13
  • 14. User-Level Threads • Cons – If a thread makes a blocking system call (or takes a page fault), the process (and all the internal threads) blocks • Can’t overlap I/O with computation • Can use wrappers as a work around – Example: wrap the read() call – Use select() to test if read system call would block » select() then read() » Only call read() if it won’t block » Otherwise schedule another thread – Wrapper requires 2 system calls instead of one » Wrappers are needed for environments doing lots of blocking system calls – exactly when efficiency matters! 14
  • 15. 15
  • 16. Implementing Threads in the Kernel A threads package managed by the kernel 16
  • 17. Kernel-Level Threads User Mode Process A Process B Process C Scheduler Kernel Mode
  • 18. Kernel Threads • Threads are implemented in the kernel – TCBs are stored in the kernel • A subset of information in a traditional PCB – The subset related to execution context • TCBs have a PCB associated with them – Resources associated with the group of threads (the process) – Thread management calls are implemented as system calls • E.g. create, wait, exit 18
  • 19. Kernel Threads • Cons – Thread creation and destruction, and blocking and unblocking threads requires kernel entry and exit. • More expensive than user-level equivalent • Pros – Preemptive multithreading – Parallelism • Can overlap blocking I/O with computation • Can take advantage of a multiprocessor 19
  • 20. Multiprogramming Implementation Skeleton of what lowest level of OS does when an interrupt occurs – a thread/context switch 20
  • 21. Thread Switch • A switch between threads can happen any time the OS is invoked – On a system call • Mandatory if system call blocks or on exit(); – On an exception • Mandatory if offender is killed – On an interrupt • Triggering a dispatch is the main purpose of the timer interrupt A thread switch can happen between any two instructions Note instructions do not equal program statements 21
  • 22. Context Switch • Thread switch must be transparent for threads – When dispatched again, thread should not notice that something else was running in the meantime (except for elapsed time) ⇒OS must save all state that affects the thread • This state is called the thread context • Switching between threads consequently results in a context switch. 22
  • 23. Thread a Thread b Simplified thread_switch(a,b) } Explicit { Thread Switch } thread_switch(b,a) { thread_switch(a,b) } { 23
  • 24. Kernel-Level Threads User Mode Process A Process B Process C Scheduler Kernel Mode
  • 25. Example Context Switch • Running in user mode, SP points to user- level stack (not shown on slide) Representation of Kernel Stack SP (Memory) 25
  • 26. Example Context Switch • Take an exception, syscall, or interrupt, and we switch to the kernel stack SP 26
  • 27. Example Context Switch • We push a trapframe on the stack – Also called exception frame, user-level context…. – Includes the user-level PC and SP SP trapframe 27
  • 28. Example Context Switch • Call ‘C’ code to process syscall, exception, or interrupt – Results in a ‘C’ activation stack building up SP ‘C’ activation stack trapframe 28
  • 29. Example Context Switch • The kernel decides to perform a context switch – It chooses a target thread (or process) – It pushes remaining kernel context onto the stack SP Kernel State ‘C’ activation stack trapframe 29
  • 30. Example Context Switch • Any other existing thread must – be in kernel mode (on a uni processor), – and have a similar stack layout to the stack we are currently using Kernel stacks of other SP threads/processes Kernel State ‘C’ activation stack trapframe Kernel State ‘C’ activation stack trapframe Kernel State ‘C’ activation stack trapframe 30
  • 31. Example Context Switch • We save the current SP in the PCB (or TCB), and load the SP of the target thread. – Thus we have switched contexts SP Kernel State ‘C’ activation stack trapframe Kernel State ‘C’ activation stack trapframe Kernel State ‘C’ activation stack trapframe 31
  • 32. Example Context Switch • Load the target thread’s previous context, and return to C SP Kernel State ‘C’ activation stack trapframe ‘C’ activation stack trapframe Kernel State ‘C’ activation stack trapframe 32
  • 33. Example Context Switch • The C continues and (in this example) returns to user mode. SP Kernel State ‘C’ activation stack trapframe trapframe Kernel State ‘C’ activation stack trapframe 33
  • 34. Example Context Switch • The user-level context is restored SP Kernel State ‘C’ activation stack trapframe Kernel State ‘C’ activation stack trapframe 34
  • 35. Example Context Switch • The user-level SP is restored SP Kernel State ‘C’ activation stack trapframe Kernel State ‘C’ activation stack trapframe 35
  • 36. The Interesting Part of a Thread Switch • What does the “push kernel state” part do??? SP Kernel State ‘C’ activation stack trapframe Kernel State ‘C’ activation stack trapframe 36
  • 37. Simplified OS/161 thread_switch static void thread_switch(threadstate_t newstate, struct wchan *wc) { struct thread *cur, *next; cur = curthread; do { next = threadlist_remhead(&curcpu->c_runqueue); if (next == NULL) { cpu_idle(); } } while (next == NULL); /* do the switch (in assembler in switch.S) */ switchframe_switch(&cur->t_context, &next->t_context); Lots of code removed – only } basics of pick next thread and run it remain 37
  • 38. OS/161 switchframe_switch switchframe_switch: /* * a0 contains the address of the switchframe pointer in the old thread. * a1 contains the address of the switchframe pointer in the new thread. * * The switchframe pointer is really the stack pointer. The other * registers get saved on the stack, namely: * * s0-s6, s8 * gp, ra * * The order must match <mips/switchframe.h>. * * Note that while we'd ordinarily need to save s7 too, because we * use it to hold curthread saving it would interfere with the way * curthread is managed by thread.c. So we'll just let thread.c * manage it. */ 38
  • 39. OS/161 switchframe_switch /* Allocate stack space for saving 10 registers. 10*4 = 40 */ addi sp, sp, -40 /* Save the registers */ Save the registers sw ra, 36(sp) sw gp, 32(sp) that the ‘C’ sw s8, 28(sp) procedure calling sw s6, 24(sp) sw s5, 20(sp) convention sw s4, 16(sp) expects sw s3, 12(sp) preserved sw s2, 8(sp) sw s1, 4(sp) sw s0, 0(sp) /* Store the old stack pointer in the old thread */ sw sp, 0(a0) 39
  • 40. OS/161 switchframe_switch /* Get the new stack pointer from the new thread */ lw sp, 0(a1) nop /* delay slot for load */ /* Now, restore the registers */ lw s0, 0(sp) lw s1, 4(sp) lw s2, 8(sp) lw s3, 12(sp) lw s4, 16(sp) lw s5, 20(sp) lw s6, 24(sp) lw s8, 28(sp) lw gp, 32(sp) lw ra, 36(sp) nop /* delay slot for load */ 40
  • 41. OS/161 switchframe_switch /* and return. */ j ra addi sp, sp, 40 /* in delay slot */ 41
  • 42. Thread a Thread b Revisiting switchframe_switch(a,b) { } Thread Switch } switchframe_switch(b,a) { switchframe_switch(a,b) } { 42