Information Technology Reference
In-Depth Information
#include<stdio.h>
#include"sthread.h"
staticvoidgo(intn);
#defineNTHREADS10
staticsthread_tthreads[NTHREADS];
intmain(intargc,char**argv)
{
intii;
for(ii=0;ii<NTHREADS;ii++){
sthreadcreate
(&(threads[ii]),&go,ii);
}
for(ii=0;ii<NTHREADS;ii++){
longret=
sthreadjoin
(threads[ii]);
printf("Thread%dreturned%ld\n",ii,ret);
}
printf("Mainthreaddone.\n");
return0;
}
voidgo(intn)
{
printf("Hellofromthread%d\n",n);
sthreadexit
(100+n);
//Notreached
}
Figure4.6: Simple multi-threaded program.
When the scheduler runs the
ii
iith thread, the thread runs the function
go()
with the value
ii
as an argument and prints
Hellofromthreadii
n
n
. The
thread then returns a value (
ii+100
) by calling
sthreadexit(ii+100)
. This
call stores the specified value in a field in the
sthreadt
object so that it can
be retrieved by the initial thread's call to
sthreadjoin()
.
The
main()
function uses
sthreadjoin()
to wait for each of the threads
it created to finish. As each thread finishes, code in
main()
reads the thread's
exit value and prints it.
Figure 4.7 shows the output of one possible run of this program. Of course,
other runs may give different interleavings of the output lines.