Multiple strands of execution in a single program are called threads.
A more precise definition is that a thread is a sequence of control within a process.
There is a whole set of library calls associated with threads, most of whose names start with pthread. To use these library calls, you must define the macro _REENTRANT , include the file pthread.h , and link with the threads library using -lpthread .
In multithreaded programs, you tell the compiler that you need this feature by defining the _REENTRANT macro before any #include lines in your program. This does three things, and does them so elegantly that usually you don't even need to know what was done:
- some functions get prototypes for a re-entrant safe equivalant. These are normally the same function name, but with _r appended so that, for example, gethostbyname is changed to gethostbyname_r .
- some stdio.h functions that are normally implemented as macros become proper re-entrant safe functions.
- the variable errno , from errno.h , is changed to call a function, which can determine the real errno value in a multithread safe way.
Create a new thread, much like fork creates a new process.
#include <pthread.h>
int pthread_create(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *), void *arg);