#include #include #include #define THREADS 8 #define START 0 #define END 1000000000 void* partial_sum(void* idp) { int id = * (int*) idp; int start = ((END - START) / THREADS) * id; int end = ((END - START) / THREADS) * (id + 1); // make sure last thread goes through end if (id == (THREADS - 1)) { end++; } // allocate space for the answer unsigned long* sum = malloc(sizeof(unsigned long)); *sum = 0; // go through range, computing the sum for (int i = start; i < end; i++) { *sum = *sum + i; } printf("Thread %d does %d to %d.\nSum = %lu.\n", id, start, end, *sum); // end the thread and return partial sum pthread_exit(sum); } int main() { // our array of threads pthread_t threads[THREADS]; // array of thread ids int ids[THREADS]; for (int i = 0; i < THREADS; i++) { ids[i] = i; pthread_create(&threads[i], NULL, &partial_sum, &ids[i]); } unsigned long grand_total = 0; for (int i = 0; i < THREADS; i++) { // join thread and get return value unsigned long* partial; pthread_join(threads[i], (void**) &partial); grand_total = grand_total + *partial; // clean up memory used free(partial); } printf("Total sum = %lu.\n", grand_total); pthread_exit(0); }