Spawning POSIX threads
Having gone through all the fundamental concepts like interleaving, locks, mutexes, and condition variables, in the previous chapters, and introducing the concept of POSIX threads in this chapter, it is the time to write some code.
The first step is to create a POSIX thread. In this section, we are going to demonstrate how we can use the POSIX threading API to create new threads within a process. Following example 15.1 describes how to create a thread that performs a simple task like printing a string to the output:
#include <stdio.h> #include <stdlib.h> // The POSIX standard header for using pthread library #include <pthread.h> // This function contains the logic which should be run // as the body of a separate thread void* thread_body(void* arg) { printf("Hello from first thread!\n"); return NULL; } int main(int argc, char** argv) { // The thread handler pthread_t thread; // Create a new thread int result...