/** * increment_personal.c * * Generate posix threads to increment a "personal" (i.e. per thread) counter. * * This is a version has correct output and runs efficiently. * * gcc -o increment_personal -lpthread increment_personal.c */ #include #include #include #include #define NUM_THREADS 8 /* create thread argument struct for thr_func() */ typedef struct _thread_data_t { int tid; } thread_data_t; /* shared data between threads */ int shared_x[NUM_THREADS]; void *thr_func(void *arg) { thread_data_t *data = (thread_data_t *)arg; int i; // printf( "thread %d has i at address %p\n", data->tid, &i ); //printf("hello from thr_func, thread id: %d\n", data->tid); for (i = 0; i < 10000000; i++) shared_x[data->tid]++; // 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]; // printf( "In main, i is at %p, shared_x at %p\n", &i, &shared_x ); /* create threads */ /* initialize shared data */ for (i = 0; i < NUM_THREADS; ++i) { shared_x[i] = 0; 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); } int total = 0; for (i = 0; i < NUM_THREADS; i++) { total += shared_x[i]; } printf("x = %d\n", total); return EXIT_SUCCESS; }