Programming POSIX threads on Linux
Part II: Mutexes, condition variables
Here, a short overview over some POSIX means to synchronize access to common resources
via mutexes and condition variables is given.
The source code
As example, I will use the source code from part I of this article,
which will be refined by using mutexes and condition variables to ensure that pthread_join()
can immediately return the return value of each thread. The waiting is done before by counting
how many threads have completed so far. If this number is less than the number of started threads,
we just wait again until both numbers are equal. Then, each call to pthread_join()
immediately returns.
The source code is againg written in C and can be downloaded here.
Compiling and linking
You can compile and link the program with the following
Makefile, which again is not
the smallest possible version.
With this Makefile in your working directory, you can simply type make to create
or re-create the executable thread.
Usage
The program is started by a command line:
thread 5
This call lets the program create 5 threads which will wait a random time interval. The main
line of the program will wait until the same number of threads has completed as are started.
Then the return value of each thread can immediately be catched via pthread_join.
Programmer's quick reference
Each program using POSIX mutexes and condition variables has to include the following header file:
#include <pthread.h>
To succesfully compile and link the program, you have to speficy the following compiler
switches and libraries, which are included in the Makefile:
-D_REENTRANT % compiler switch
-lpthreads % linker lib
Here are the most important POSIX functions concerning the basics of synchronization programming.
For a quick reference, they are given as function prototypes. The usage is shown in the
example source code.
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int pthread_mutex_lock(pthread_mutex_t* mutex);
return value: 0 if OK, positive error code otherwise
int pthread_mutex_unlock(pthread_mutex_t* mutex);
return value: 0 if OK, positive error code otherwise
int pthread_mutex_trylock(pthread_mutex_t* mutex);
return value: EBUSY if the mutex is locked
int pthread_cond_wait(pthread_cont_t* cond, pthread_mutex_t* mutex);
return value: 0 if OK, positive error code otherwise
int pthread_cond_signal(pthread_cond_t* cond);
return value: 0 if OK, positive error code otherwise
Literature
- R. W. Stevens, Unix Network Programming, vol. II: Interprocess Communications,
Prentice-Hall.
A very good book in two volumes which can be seen as classic text about every aspect of
Unix network programming, including sockets, threads, IPC and RPC.
|