A Pthreads Tutorial, written by Andrae Muys

All Unix's are multi-tasking operating systems. The process model used by unix permits a user to run multiple processes simultaneously making it one of the most powerful and flexible multi-programming models in use today.

Under the traditional unix model, processes are all created in the same way, by using the fork() system call.

Fork() produces a second copy of the calling process. This second copy is identical to the original, except that the return value of fork() in the child = 1, while the return value of fork() in the parent = the child's pid. So the normal use of fork() is:

[do parent stuff]
ppid = fork ();
if (ppid < 0) {
        fork_error_function ();
} else if (ppid == 1) {
        child_function ();
} else {
        parent_function ();

Note that this only works because fork() returns two completely independent copies of the original process. Each process has its own address space, with its own copies of its variables, which are completely independent of the same variables in the other process (the only exception to this is with some SysV IPC variables, but these are special cases).

This independence, while providing memory protection and therefore stability, causes problems when you want to have multiple processes working on the same task/problem. Yes you can use pipes or SysV IPC, but there are still serious problems.

For these reasons, and others, threads or Light Weight Processes(LWP) can be very useful. Threads share a common address space, and are often scheduled internally in a process, thereby avoiding a lot of the inefficiencies of multiple processes.

One very popular API for threading an application is pthreads, also known as POSIX threads, P1003.1c, or ISO/IEC 9945-1:1990c. This API is the subject of todays tutorial.

<<< Contents >>>

Andrae Muys