#include #include #include #include #define SIZE 10 static int nthreads = 5, delay = 5, sum[SIZE]; pthread_mutex_t sum_lock[SIZE]; int parse_args(int argc, char *argv[], int *nthreads, int* delay){ if ((argc != 3) || ((*nthreads = atoi(argv[1])) == 0) || ((*delay = atoi(argv[2])) == 0)) { fprintf (stderr, "Usage: %s nthreads delay\n", argv[0]); return(-1); }; return(0); } void spin(){ int j; for(j=0; j< delay; j++); } void *updater(void *ptr){ int j; for(j = 0; j < SIZE; j++){ int i; pthread_mutex_lock(&sum_lock[j]); spin(); i = sum[j]; spin(); i++; spin(); sum[j] = i; pthread_mutex_unlock(&sum_lock[j]); } spin(); pthread_exit(NULL); } int main(int argc, char *argv[]){ int i; if(parse_args(argc, argv, &nthreads, &delay) < 0){ exit(EXIT_FAILURE); } else { pthread_t threads[nthreads]; for(i = 0; i < SIZE; i++){ sum[i] = 1; pthread_mutex_init(&sum_lock[i], NULL); } for(i = 0; i < nthreads ; i++) pthread_create(&threads[i],NULL,updater,NULL); for(i = 0; i < nthreads ; i++) pthread_join(threads[i],NULL); for(i = 0; i < SIZE; i++) fprintf(stderr, "sum[%d] = %d\n", i, sum[i]); exit(EXIT_SUCCESS); } }