The most popular threading standard used with C is POSIX Threads, or Pthreads for short. The POSIX standard defines a thread model and an interface for creating and controlling threads. Most versions of UNIX provide an implementation of Pthreads.
Using Pthreads is like using most C libraries:
- You include headers files at the beginning of your program.
- You write code that calls functions defined by Pthreads.
- When you compile the program, you link it with the Pthread library.
For my examples, I include the following headers:
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <semaphore.h>
The first two are standard; the third is for Pthreads and the fourth is for semaphores. To compile with the Pthread library in
gcc, you can use the
-l option on the command line:
gcc -g -O2 -o array array.c -lpthread
This compiles a source file named
array.c with debugging info and optimization, links with the Pthread library, and generates an executable named