Thread Library - CS 702 - Fall 2004
Loyola College >
Department of Computer Science >
Dr. James Glenn >
CS 702 >
Examples and Lecture Notes >
Thread Library
A simple thread library for Linux-x86 and g++ 3.2.2
Goals
- Java-like threads
- threads should subclass Thread
- threads are started by invoking start
- thread entry point is is run
- threads die when run returns
- cooperative multitasking through the yield method
- main creates and starts threads, then invokes
Scheduler::start() to begin executing them. When no threads
are running, execution continues in main after the invokation of
start.
Design
- Scheduler has a queue containing threads that are active
but not currently running.
- Each thread needs its own stack; each instance of Thread
has fields to keep track of each stack.
- yield is static so it can be called from anywhere by the
currently executing thread; we need a place to store a pointer to the
currently executing thread so yield can get it.
- Scheduler::start must save main's registers,
including its stack pointer.
- yield must save the current value of ESP (as well
as other registers) and transfer control to Scheduler::schedule
for selection of another thread to execute.
- Scheduler::schedule picks a thread out of the queue and
invokes that thread's activate method, which
needs to restore the selected thread's
stack and registers and return to where it yielded.
- start must set up a thread's stack in such a way that
Scheduler::schedule will start it in run and so that
once run returns control gets to terminate, which
can invoke Scheduler::schedule to select another thread.
Code
- The thread library:
- An example of using the thread library:
Thread Data Structures
Yielding to Another Thread
- save registers on stack of yielding thread (in Thread::yield assembly)
- save yielding thread's new stack pointer in Thread structure (in Thread::yield assembly)
- enqueue the yielding thread (in Scheduler::threadYielded C++)
- dequeue next thread (in Scheduler::scheduleThread C++)
- save address of next thread (in Thread::activate assembly)
- restore next thread's registers (including ESP) and return to it (in Thread::activate assembly)
Starting a Thread
- put data in new thread's stack (in Thread::start assembly)
- store new thread's stack pointer in Thread structure (in Thread::start assembly)
- enqueue new thread (in Scheduler::startThread C++)
Starting the Scheduler
- save main's registers on main's stack (in Scheduler::start assembly)
- save main's stack pointer in originalESP (in Scheduler::start assembly)
- dequeue next thread (in Scheduler::scheduleThread C++)
- save address of next thread (in Thread::activate assembly)
- restore next thread's registers (including ESP) and return to it (in Thread::activate assembly)
Blocking a Thread