Synchronization

Race conditions are a common problem when using threads, and solving race conditions without introducing deadlock (a thread that can no longer execute due to logic bugs with thread synchronization logic) is a complicated topic deserving of its own book.

The following example attempts to demonstrate the issues with potential race conditions:

#include <array>#include <iostream>#include <pthread.h>int count = 0;void *mythread(void *ptr){    count++;}main(){    while (true) {        count = 0;        for (auto i = 0; i < 1000; i++) {            std::array<pthread_t, 8> threads;            for (auto &t : threads) {                pthread_create(&t, nullptr, mythread, nullptr);            }            for (auto &t : threads) {                pthread_join(t, nullptr);            }        }        std::cout << "count: " << count << '\n';    }}// > g++ ...

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.