Starting a thread

Now that we've seen how to start another process, let's see how to start another thread.

Any thread can create another thread in the same process; there are no restrictions (short of memory space, of course!). The most common way of doing this is via the POSIX pthread_create() call:

#include <pthread.h>

int
pthread_create (pthread_t *thread,
                const pthread_attr_t *attr,
                void *(*start_routine) (void *),
                void *arg);

The pthread_create() function takes four arguments:

thread
A pointer to a pthread_t where the thread ID is stored.
attr
An attributes structure.
start_routine
The routine where the thread begins.
arg
An argument passed to the thread's start_routine.

Note that the thread pointer and the attributes structure (attr) are optional—you can pass them as NULL.

The thread parameter can be used to store the thread ID of the newly created thread. You'll notice that in the examples below, we'll pass a NULL, meaning that we don't care what the ID is of the newly created thread. If we did care, we could do something like this:

pthread_t tid;

pthread_create (&tid, …
printf ("Newly created thread id is %d\n", tid);

This use is actually quite typical, because you'll often want to know which thread ID is running which piece of code.

Note: A small subtle point. It's possible that the newly created thread may be running before the thread ID (the tid parameter) is filled. This means that you should be careful about using the tid as a global variable. The usage shown above is okay, because the pthread_create() call has returned, which means that the tid value is stuffed correctly.

The new thread begins executing at start_routine(), with the argument arg.