/* Example program with pthreads. * * Compute the sum of the first N square natural numbers, with * each square being computed by a different pthread. */ #include #include #include static void * thread_body(void *opaque) { int *intp = (int *)opaque; /* Compute the square in-loco. */ *intp = (*intp) * (*intp); /* Return the input pointer back through the return value. */ pthread_exit(intp); /* Execution never arrives here. */ } int main(int argc, char **argv) { pthread_t *tids; /* array of thread identifiers */ int *squares; /* array of integers */ int n = 5; /* default number of threads is 5 */ int sum = 0; int i; if (argc > 1) { /* User provided some command-line arguments, we need * to validate them. */ int m = atoi(argv[1]); if (m > 0 && m <= 10000) { /* valid */ n = m; } else { /* invalid */ printf("Input argument is not a valid number of threads " "in [1..10000]\n"); return -1; } } /* Allocate the two arrays. */ tids = malloc(n * sizeof(tids[0])); if (tids == NULL) { printf("Error: failed to allocate tids\n"); return -1; } squares = malloc(n * sizeof(squares[0])); if (squares == NULL) { free(tids); printf("Error: failed to allocate squares\n"); return -1; } /* Create a pool of threads. */ for (i = 0; i < n; i ++) { int ret; squares[i] = i+1; /* the natural number, pthread input */ ret = pthread_create(&tids[i], NULL, thread_body, &squares[i]); if (ret) { printf("Error: pthread_create() failed [err=%d]\n", ret); } } /* Wait for the thread to finish their job. */ for (i = 0; i < n; i ++) { int *retptr; int ret = pthread_join(tids[i], (void **)&retptr); if (ret) { printf("Error: pthread_join() failed [err=%d]\n", ret); } else { printf("Thread #%d returned %d\n", i + 1, *retptr); } } /* Collect threads output and compute the sum of squares. */ for (i = 0; i < n; i++) { sum += squares[i]; } free(squares); free(tids); printf("The first %d squares sum up to %d\n", n, sum); return 0; }