Dana Vrajitoru
B424 Parallel and Distributed Programming

The Pthread Library

Basic functions

Creating - terminating threads
Initially, the main() program comprises a single, default thread. All other threads must be explicitly created by the programmer, by calling the following function.

int pthread_create (thread, attributes, start_function, argument);

This creates a thread with the specified attributes and executes the start function within it. The function may have one argument that must be passed as a void-type pointer (can be a pointer to a complex data structure). The function returns 0 if the thread was created successfully.

Once the thread has been created, it has a unique identity that can be found with the function:
int pthread_self();

There are several ways in which a thread may be terminated:

Thread synchronisation:
int pthread_join (pthread_t thread, void **status);
Forces the parent thread for the one used as argument to wait until the thread has finished its execution. The value returned by the thread in the exit function can be found as the second parameter, if not NULL.

Protecting a critical section: mutex variables.

To create a mutex lock, just declare a variable of the appropriate type:
pthread_mutex_t mutex;

The lock must then be initialized:
pthread_mutex_init(&mutex, NULL);

Before entering the critical section, each thread should lock the mutex:
pthread_mutex_lock(&mutex);

When leaving the critical section, the thread must unlock the mutex:
pthread_mutex_unlock(&mutex);