/* This program spawns NUM_THREADS threads, each of which increments a global sum variable LOOP_NUM times. There is locking in this program, so we expect the same behavior when executing several times. For example, if NUM_THREADS = 50 and LOOP_NUM = 10000, the expected output will be 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; // mutex used to lock when incrementing sum_total static pthread_mutex_t sum_lock; // 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++) { // obtain the lock so we can increment sum_total pthread_mutex_lock(&sum_lock); sum_total++; // release the lock for another thread to use pthread_mutex_unlock(&sum_lock); } 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]; // initialize mutex pthread_mutex_init(&sum_lock, NULL); // 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; // clean up mutex pthread_mutex_destroy(&sum_lock); return 0; }