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++ ...