But POSIX threads (aka pthreads) comes with all standard UNIX and Linux installations of gcc.
- Primary pthreads data type is the pthread_t, which is an opaque type that helps manage how a C function is executed in its own thread of execution.
- Only pthreads functions we'll concern ourselves with (before moving on to C++ threads) are pthread_create and pthread_join.
- Here's a very small sample program (online version is right here):
#include <stdio.h> // provides printf, which is thread-safe
#include <pthread.h> // provides pthread_t type, thread functions
static void *recharge(void *args) {
printf("I recharge by spending time alone.\n"); // printf is thread-safe
return NULL;
}
static const size_t kNumIntroverts = 6;
int main(int argc, char *argv[]) {
printf("Let's hear from %zu introverts.\n", kNumIntroverts);
pthread_t introverts[kNumIntroverts];
for (size_t i = 0; i < kNumIntroverts; i++)
pthread_create(&introverts[i], NULL, recharge, NULL);
for (size_t i = 0; i < kNumIntroverts; i++)
pthread_join(introverts[i], NULL);
printf("Everyone's recharged!\n");
return 0;
}
- Program above declares an array of six pthread_t handles.
- Program then initializes each pthread_t (via pthread_create) by installing the recharge as the routine the each of the threads should follow while executing.
- All thread functions must take a void * and return one as well. That's generic programming in C. #sadface
- Second argument to pthread_create allows thread attibutes (thread priorities, etc.) to be set. We'll always pass in NULL to accept the defaults.
- Fourth argument is passed verbatim to the thread routine once the thread is launched.
In this case, there are no arguments, so we elect to pass in NULL.
- Each recharge thread is eligible for processor time the instant the surrounding pthread_t is fully configured.
- Six threads compete for thread manager's attention, and we have very little control over what choices the thread manager makes.
- The 0th thread will probably get processor time first.
- Probable and guaranteed are two different words.
- We have no official word on the permutation of possible schedules the thread manager will go with.
- pthread_join is to threads what waitpid is to processes. The main thread blocks until the argument thread exits. (Key difference: the waiting thread need not have spawned the one it blocks on).