Docsity

Thread Implementation - Lecture Notes | CS 423, Study notes of Operating Systems

Partial preview of the text

Download Thread Implementation - Lecture Notes | CS 423 and more Study notes Operating Systems in PDF only on Docsity!

CS 423: Thread

implementation

Sam King / Klara Nahrstedt

Thread impl. on uni-proc.

• So far, we’ve been assuming that we have

enough physical process to run each thread

on its own processor

  • But threads are useful also for running on a uni-

processor (web server example)

  • How to give the illusion of infinite physical

processors on a single processor?

• Play analogy

Thread context

• This information is called the thread “context”

and is stored in a “thread control block” when

the thread isn’t running

  • To save space, share code among all threads
  • To save space, don’t copy stack to the thread

control block.

  • Multiple stacks in same address space, copy stack pointer in thread control block

Thread context

• Keep thread control blocks for threads

that aren’t running on a queue of ready

threads

– Thread state can now be running, ready, or

blocked

Returning control to OS

• How does thread return control back to

the OS (so system ca save state of

current thread and run new one)?

Choosing the next thread to run

  • If no ready thread, just loop idly
    • Loop switches to a thread when one is ready
  • If 1 ready thread, run it
  • If more than 1 ready, choose one
    • FIFO
    • Priority queue (more on this later)

Loading context of new thread

  • How to load the context of the next thread to run and

run it?

Example of thread switching

Thread 1 print “start thread 1 ” yield() print “end thread 1 ” Thread 2 print “start thread 2 ” yield() print “end thread 2 ” Yield print “start yield (thread %d)” switch to next thread (swapcontext) print “end yield (current thread %d)

Thread states

Running

Ready Blocked

Creating a new thread

• Overall: create state for thread and add it to

the ready queue

  • When saving a thread to its thread control block,

we remembered its current state

  • We can construct the state of new thread as if it

had been running and got switched out

• Steps

  • Allocate and initialize new thread control block
  • Allocate and init new stack
    • Use C++ new
    • Init sp (using makecontext in MP2)
  • Add to ready queue

• Fork related but different

Do the following

work?

Parent() { thread_create print “parent work” print “parent cont” } Child() { print “child work” } Parent() { thread_create print “parent work” thread_yield print “parent cont” } Child() { print “child work” }

Join: wait for another thread to finish Parent() { thread_create lock print “parent works” unlock join print “parent cont” } Child() { lock print “child works” unlock }