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:
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.
The new thread begins executing at start_routine(), with the argument arg.