// Remember to compile with -pthread #include #include #include using std::cout; using std::cerr; using std::endl; const int NUM_THREADS = 50; // implicitly static const int LOOP_NUM = 500; static int sum_total = 0; static pthread_mutex_t sum_lock; void *thread_main(void *arg) { for (int i = 0; i < LOOP_NUM; i++) { //pthread_mutex_lock(&sum_lock); sum_total++; //pthread_mutex_unlock(&sum_lock); } return NULL; } int main(int argc, char** argv) { pthread_t thds[NUM_THREADS]; pthread_mutex_init(&sum_lock, NULL); for (int i = 0; i < NUM_THREADS; i++) { if (pthread_create(&thds[i], NULL, &thread_main, NULL) != 0) { cerr << "pthread_create failed" << endl; } } 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; pthread_mutex_destroy(&sum_lock); return 0; }