Computer with Single Processor

Single threaded Program on Computer with Single Processor

  • A program runs on a single processor

    • The program's instructions are loaded from memory
    • The instructions are executed on the processor
  • Registers store information needed to execute the current instruction

    • Stack pointer
    • Operand guards
    • etc
  • Data is loaded from memory into processor registers as needed

  • If modified, the new value is then written back to memory

Multi threaded Program on Computer with Single Processor

  • Implemented by "time slicing"

  • Each thread runs on the CPU for a short time, e.g.

    • Thread A starts, runs for a short period, then pauses
    • Thread B starts, runs for a short period, then pauses
    • Thread C starts, runs for a short period, then pauses
    • Thread B runs again from where it left off, then pauses
    • Thread C runs again from where it left off, then pauses
  • This is done very quickly

  • The threads appears to run concurrently

Thread Scheduler

  • A scheduler controls how threads execute

    • Similar to the operating system's scheduler for processes
  • Pre-emptive task switching

    • A thread can run for a certain time
    • The scheduler will interrupt the thread when it has used up its time slot
    • Another thread can then run
    • The scheduler will make interrupted thread "sleep"

Thread Scheduling

  • Thread may start in any order

  • A thread may be interrupted at any time

  • A thread may be restarted at any time

  • While a thread is sleeping, another thread may run

    • This can run the same code as the inactive thread
    • It can access data which it shares with the inactive thread
  • The execution of the thread is interleaved

    • Thread B starts and is interrupted
    • Thread A starts and is interrupted
    • Thread C starts and is interrupted
    • Thread A executes some more instructions and is interrupted
    • Thread B executes some more instructions and is interrupted

Disadvantages of Time Slicing

  • Requires a "context switch"
  • Save the processor state for the current thread
    • Current values of processor registers
    • Program's instruction pointer
    • etc
  • Load the saved processor state for the next thread
    • Values of processor registers when stopped, etc
    • May also have to reload the thread's instructions and data
  • The processor cannot execute any instructions during a context switch