In this—the second major portion of this first chapter on multithreading—we shall now focus on the mechanics: using the pthreads API, how exactly does the programmer create and manage threads in an effective fashion? We will explore the essential pthreads API interfaces to fulfill this key purpose; this knowledge is the building block for writing functional and performance-friendly pthreads applications.
We will take you through the thread life cycle in terms of API sets—creating, terminating, joining upon (waiting for), and in general, managing the threads of a process. We will also cover thread stack management.
This, of course, implies that we have a pthreads runtime library installed on the Linux system. On modern Linux distributions, this will certainly be the case; it's only if you are using a rather exotic embedded Linux that you will have to verify this. The name of the pthreads library on the Linux platform is libpthread.
A couple of key points regarding the pthread APIs are as follows:
- All pthread APIs require the <pthread.h> header file to be included in the source.
- The API often uses the object-oriented concepts of data hiding and data abstraction; many data types are internal typedefs; this design is deliberate: we want portable code. Thus, the programmer must not assume types and must work with the provided helper methods where applicable to access and/or query data types. (Of course, the code itself is the usual procedural C; nevertheless, many concepts are modeled around object orientation. Interestingly, the Linux kernel also follows this approach.)