Hardware Reference
In-Depth Information
The reason behind this is likely that it was thought that the traditional Unix
errno
approach would be phased out in the near future (at the time POSIX threads were being
standardized). The original use of
errno
was as follows:
extern int errno;
However, this approach didn't work for threaded programs. Imagine two threads
concurrently opening files with
open(2)
, which sets the
errno
value upon failure. Both
threads cannot share the same
int
value for
errno
.
Rather than change a vast body of code already using
errno
in this manner, other
approaches were implemented to provide each thread with its own private copy of
errno
.
This is one reason that programs today using
errno
must include the header file
errno.h
.
The header file takes care of defining the thread specific reference to
errno
.
Because the pthread standard was developing before the
errno
solution generally
emerged, the pthread library returns the error code directly when there is an error and
returns zero when the call is a success. If Unix were to be rewritten from scratch today, all
system calls would probably work this way.
pthread_create(3)
The function
pthread_create(3)
is used to create a new thread of execution. The
function call looks more daunting than it really is:
int pthread_create(
pthread_t
thread,
const pthread_attr_t
∗
attr,
∗
void
(
start_routine)(void
),
∗
∗
∗
void
arg
∗
);
The call to
pthread_create(3)
creates a new stack, sets up registers, and performs
other housekeeping. Let's describe the arguments:
thread
: This first argument is simply a pointer to a
pthread_t
variable to receive the created thread's ID value. The ID value
allows you to query and control the created thread. If the call
succeeds, the thread ID is returned to the calling program.
attr
: This is a pointer to a
pthread_attr_t
attribute object
that supplies various options and parameters. If you can accept
the defaults, simply supply zero or
NULL
.
start_routine
: As shown in the following code, this is simply
the name of a start routine that accepts a void pointer and
returns a void pointer.