The basics of POSIX threads

The most basic use of a thread is to create it, and then join the thread, which, in effect, waits for the thread to finish its work before returning as follows:

#include <iostream>#include <pthread.h>void *mythread(void *ptr){    std::cout << "Hello World\n";    return nullptr;}int main(){    pthread_t thread1;    pthread_t thread2;    pthread_create(&thread1, nullptr, mythread, nullptr);    pthread_create(&thread2, nullptr, mythread, nullptr);    pthread_join(thread1, nullptr);    pthread_join(thread2, nullptr);}// > g++ -std=c++17 scratchpad.cpp -lpthread; ./a.out// Hello World// Hello World

In the preceding example, a mythread() function is created with the signature (void *)(*)(void *), which is required by POSIX threads. In this ...

Get Hands-On System Programming with C++ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.