// Sample code that demonstrates a data race between threads reading and writing // from the same shared global variable in Static Data. // Interleaving of reads and writes will sometimes cause printed sum to be less // than expected. // // Remember to compile with -pthread #include #include using std::cout; using std::cerr; using std::endl; static constexpr int kNumThreads = 50; static constexpr int kLoopNum = 1000; static int sum_total = 0; // increment sum_total LOOP_NUM times void *thread_main(void *arg) { for (int i = 0; i < kLoopNum; i++) { sum_total++; } return nullptr; // return type is a pointer } int main(int argc, char** argv) { for(int i = 0; i < kNumThreads * kLoopNum; i++){ sum_total++; } cout << "Total: " << sum_total << endl; return EXIT_SUCCESS; }