/* This program spawns NUM_THREADS threads, each of which increments a global sum variable LOOP_NUM times. There is no locking in this program, so we expect different behavior when executing several times. For example, if NUM_THREADS = 50 and LOOP_NUM = 10000, the expected output will be 500000. However due to lack of locking, we may see numbers between 400000 and 500000 Don't forget to compile with the -pthread flag! */ #include #include using std::cout; using std::cerr; using std::endl; const int NUM_THREADS = 50; // implicitly static const int LOOP_NUM = 10000; // global variable that is incremented by thread_main() static int sum_total = 0; // This is the routinve that is executed by each of the threads spawned by main(). // Increments sum_total LOOP_NUM times. void *thread_main(void *arg) { for (int i = 0; i < LOOP_NUM; i++) { sum_total++; } return NULL; } // Main spawns each thread with pthread_create() and tells them to execute thread_main() int main(int argc, char** argv) { // an array of all of our threads pthread_t thds[NUM_THREADS]; // spawn threads for (int i = 0; i < NUM_THREADS; i++) { // create new thread and tell it to execute thread_main() if (pthread_create(&thds[i], NULL, &thread_main, NULL) != 0) { cerr << "pthread_create failed" << endl; } } // halt execution of main and wait for each of the threads to finish for (int i = 0; i < NUM_THREADS; i++) { if (pthread_join(thds[i], NULL) != 0) { cerr << "pthread_join failed" << endl; } } cout << "Total: " << sum_total << endl; return 0; }