hello, world
#include <stdio.h>
#include <stdlib.h>
#include <thread.h>
static void *print(void*);
int main()
{
int okend = EXIT_SUCCESS;
(void)thr_create(0,0, print, (void *)"hello, ", 0L,0);
(void)thr_create(0,0, print, (void *)"world.\n", 0L,0);
thr_exit(&okend);
/*NOTREACHED*/
}
static void *print(void *s)
{
(void)printf(s);
return NULL;
}
hello, world
``hello, world''
shows the traditional first program written when one enters
a new regime of the UNIX programming environment.
In this example,
we create one thread to output ``"hello, "''
and a separate thread to output ``"world.\n"''
Despite its brevity,
this example illustrates several points about programming with the
Threads Library:
-
The argument types and the return type of
the printf (see
fprintf(3S))
function disqualify it as the starting point of a thread.
A ``wrapper'' function (print) had to be devised.
-
There is no need for the initial thread to wait for the completion
of the two threads running print.
The process is automatically terminated after both of the printing
threads complete.
NOTE:
The use of
thr_exit(3thread)
is important.
The use of return from main
or allowing main to run off the closing brace
is translated to a call to the
exit(2)
system call.
That system call generally terminates the process before the printing
threads can produce their output.
-
The order of the output is not guaranteed.
In most cases
the thread that is created first will be able to output ``"hello, "''
before the following thread outputs ``"world.\n"''
Occasionally, the order is reversed.
Next topic:
Basic threads management example
Previous topic:
Examples
© 2004 The SCO Group, Inc. All rights reserved.
UnixWare 7 Release 7.1.4 - 27 April 2004