/** * increment.c * * Use posix threads to increment a global counter. * * This version uses a mutex lock to prevent a race condition. * * gcc -o increment -lpthread increment.c */ #include #include #include #include #define NUM_THREADS 10 /* create thread argument struct for thr_func() */ typedef struct _thread_data_t { int tid; } thread_data_t; /* shared data between threads */ int shared_x; pthread_mutex_t count_mutex; void *thr_func(void *arg) { thread_data_t *data = (thread_data_t *)arg; //printf("hello from thr_func, thread id: %d\n", data->tid); pthread_mutex_lock(&count_mutex); for (int i = 0; i < 100000000; i++) { shared_x++; } pthread_mutex_unlock(&count_mutex); // printf("x = %d\n", shared_x); pthread_exit(NULL); } int main(int argc, char **argv) { pthread_t thr[NUM_THREADS]; int i, rc; /* create a thread_data_t argument array */ thread_data_t thr_data[NUM_THREADS]; /* initialize shared data */ shared_x = 0; pthread_mutex_init (&count_mutex, NULL); /* create threads */ for (i = 0; i < NUM_THREADS; ++i) { thr_data[i].tid = i; if ((rc = pthread_create(&thr[i], NULL, thr_func, &thr_data[i]))) { fprintf(stderr, "error: pthread_create, rc: %d\n", rc); return EXIT_FAILURE; } } /* block until all threads complete */ for (i = 0; i < NUM_THREADS; ++i) { pthread_join(thr[i], NULL); } pthread_mutex_destroy(&count_mutex); printf("x = %d\n", shared_x); return EXIT_SUCCESS; }