Synchronization

Another notable difference between POSIX threads and C++ threads is the simplicity of thread synchronization. Like the POSIX APIs, C++ provides the ability to create a mutex, as follows:

#include <mutex>#include <thread>#include <iostream>int count = 0;std::mutex mutex;void mythread(){    mutex.lock();    count++;    mutex.unlock();}main(){    std::thread t1{mythread};    std::thread t2{mythread};    t1.join();    t2.join();    std::cout << "count: " << count << '\n';}// > g++ -std=c++17 scratchpad.cpp -lpthread; ./a.out// count: 2

In the preceding example, we create a thread that increments a shared counter, which is surrounded by a C++ std::mutex{}, in effect creating a guarded critical region. We then create two threads, wait for them to complete, ...

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.