|
| |
![]() |
|
Introduction to ThreadsNachos threads share address space with each other. Thus, the state of a thread includes the program counter, the processor registers, and the execution stack. The Nachos global variable currentThread is a pointer to the thread that currently occupies the CPU. The thread is implemented through the class Thread. There are several operations that can be performed on a Thread object. The basic operations are Fork, Sleep, Finish and Yield. The functionality of each of them is described below. ForkThis operation creates a new thread by forking a Thread object. The Fork method is implemented as the following steps:
The code below creates a new thread called myThread by simply creating a Thread object with the class constructor and then fork it. Passing the function "functionToRun" (through a function pointer) will force myThread to run the function that "functionToRun" points to. The second argument is an argument to be passed to the function pointed out. Although the definition only allows a single argument to be passed to the function, it is possible to pass multiple arguments by making them fields of a structure, and passing a pointer to the structure as the argument.
myThread = new Thread("this is my thread");
myThread->Fork("functionToRun",0);
YieldThis operation relinquishes the CPU if another thread is ready to run. When this operation is called by a thread, it's up to the scheduler to decide the next thread that shall be given CPU access. The code below shows how a thread, currentThread, wants to unoccupy the CPU. If any other thread is ready to run it will be granted access to the CPU and currentThread will be enqueued to the ready queue. However, if the ready queue is empty, currentThread will continue its execution.
currentThread->Yield();
SleepThis operation also relinquishes the CPU (as Yield does). This methods is used when the current thread shall be blocked and wait on a synchronization variable (Semaphore, Lock, or Condition. see chapter synchronization). The difference between Sleep and Yield is that Sleep forces the calling thread to block. The scheduler now tries to find another thread to run. Note that only currentThread can call Sleep. Later on, another thread will wake the thread up again, and put it back onto the ready queue. The code below shows how the current thread puts itself to sleep.
currentThread->Sleep();
FinishWhen a thread has finished executing its forked procedure, it will call the Finish operation. The thread will now "die" and the scheduler will pick the next thread in line on the ready queue and give it CPU access. Note that only currentThread can call Finish. The code below shows how a thread finishes itself.
currentThread->Finish();
|
Nachos Introduction Tutorials |
| © 1999-2008 - All rights reserved. CS tutorials™ and the logo are registered trademarks of CS tutorials. | |