Threads

What is a Thread

A unit of execution, belongs to a process.
Each Thread has a

  • State
  • Stack (with local variables)
  • Program Counter
  • Bunch of Registers.

Where to Implement Threads

User Level

  • Thread management (switching etc) = fast
    • Thread management (creating ,yielding, waiting, etc) are done in a system library
  • More application memory than kernel memory = heaps of threads
    • Threads managed in user space
  • Can be tuned to application
  • Can be implemented on any OS regardless of threading
  • No interrupt/pre-emption = threads have to yield voluntarily
    • One bad thread can steal all CPU time
  • Can't take advantage of multiple CPUs (one process = one thread in CPU mind)
  • Blocking = less efficient
    • Threads that block on a system call block the whole process
    • Unless we wrap a system call with a check to see if it'll work (slower+less elegant)

Kernel Level

  • Thread creation/destruction blocking/unblocking done in kernel mode = expensive (requires entering and exiting kernel mode)
  • But we get preemptive multithreading and proper parallelism

Thread Details

State

thread%20state.png

Context

Context is the state/information about a process/thread. When we switch threads/processes, we do a context switch. We save all the information needed in order to resume running of the thread, then we load on the info for the new thread.

Context switches can happen any time the OS is invoked - e.g. a system call, an exception, or an interrupt (this is basically the timer interrupt's job). They can happen between any 2 instructions, so we have to save state perfectly.

Each thread has a stack in the kernel to keep track of it (as said above). When a syscall (/etc) happens, we push a 'trapframe' onto this stack - the state info required to resume running (SP, PC, etc). Then we push on the c code to process whatever happened, then we push on any other kernel context stuff. The kernel context is mostly any variables (Registers) that we need preserved.

Then we switch to another thread, and pop back off the all that same stuff from its kernel stack.

thread%20switch%20stack.png

Preemption

Sometimes threads will voluntarily finish their work and let someone else run. If they don't we pre-empt them - forcibly pause them.