Skip to content

Instantly share code, notes, and snippets.

@josephlewis42
Created January 1, 2016 02:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josephlewis42/313df3183156754aafba to your computer and use it in GitHub Desktop.
Save josephlewis42/313df3183156754aafba to your computer and use it in GitHub Desktop.
// Compile with: gcc prog.c -lpthread
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
const int NUM_THREADS = 5;
// typically you'd set this to whatever your real work is
const int num_digits = 10;
const int digits[num_digits] = {1,2,3,4,5,6,7,8,9,10};
// This is the function we want to parallelize
void *Sum(void *param) {
long threadid = (long) param;
long mysum = 0;
// divide up the work based on this thread's ID
int chunksize = num_digits / NUM_THREADS;
int start = chunksize * threadid;
int end = start + chunksize;
for(int i = start; i < end; i++) {
mysum += digits[i];
}
printf("Thread %ld got sum: %ld\n", threadid, mysum);
// We return our result here so the main thread can tally
// pthreads uses void* because it doesn't know what type you want to return
// typically you'd return a pointer to something if the work was intensive
return (void*) mysum;
}
int main(int argc, char *argv[]) {
// Keep a list of all the threads we're going to create
pthread_t threads[NUM_THREADS];
for(long t = 0; t < NUM_THREADS; t++) {
printf("Main creating thread %ld\n", t);
pthread_create(&threads[t], NULL, Sum, (void *)t);
}
long sum = 0;
void* result;
// Wait for our threads to all finish and get their results
for(int t = 0; t < NUM_THREADS; t++) {
pthread_join(threads[t], &result);
sum += (long) result;
}
printf("All threads finished, sum is: %ld\n", sum);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment