Information Technology Reference
In-Depth Information
//funcisapointertoaprocedurewewantthethreadtorun
//argistheargumenttobepassedtothatprocedure
void
thread_create(sthread_t*thrd,void(*func)(int),intarg)
{
//AllocateTCBandstack
TCB*tcb=newTCB();
thrd->tcb=tcb;
tcb->stack_size=INITIAL_STACK_SIZE;
tcb->stack_base=newStack(INITIAL_STACK_SIZE);
//Initializeregistervalues
tcb->setStackPointer(stack);
tcb->setInstructionPtr(stub); //Don'tcallfunc()directly
tcb->setArg0Register(func); //Tellstubtocallfunc()
tcb->setArg1Register(arg); //Tellstubtouseargwhenitcallsfunc()
...
//Putthreadin Ready state
readyList->add(tcb);
//Puttcbonreadylist
}
void
stub(void(*func)(int),intarg)
{
(*func)(arg); //Executethefunctionfunc()
thread_exit(0); //Iffunc()doesn'tcallexit, callithere
}
Figure4.11: Pseudo-code for thread creation. For convenience, we assume
that the stack grows from low addresses to high ones and that arguments to
functions are passed in registers. The code would be somewhat different for
the x86 architecture, where the stack grows down and arguments are passed
on the stack.
4.4.1
Creating a thread
Figure 4.11 shows the pseudo-code to allocate a new thread. Since we have to
say what we want the thread to do, when we call sthreadcreate() we hand
it a pointer to a procedure func() and an argument that we would like to pass
to that procedure arg . Then, when the thread we create runs, it will execute
func(arg) .
Allocating per-thread state. To allocate a thread, we must first allocate
its per-thread state. As the pseudo-code illustrates, the thread constructor
therefore allocates a thread control block (TCB) and stack. The TCB is just
a data structure with fields for the state we want to be able to maintain for
a thread. The stack is just an area of memory like any other data structure
allocated in memory.
Note that we must choose some size for the allocated stack. Some imple-
mentations allocate a xed-sized stack, and it is a bug for a thread's stack to
overflow the fixed-sized stack. Other systems allocate an initial stack of some
 
Search WWH ::




Custom Search