Skip to content

Instantly share code, notes, and snippets.

@huonw
Created March 7, 2012 10:15
Show Gist options
  • Save huonw/1992378 to your computer and use it in GitHub Desktop.
Save huonw/1992378 to your computer and use it in GitHub Desktop.
pthread v0.0.0.0.0.1
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
// debugging
#define HERE() printf("%s:%s:%d\n", __FILE__, __func__, __LINE__)
#define LENGTH 100000000
#define NUM_THREADS 2
// array with stored length
typedef struct {
unsigned len;
unsigned long long * data;
} len_array;
/* the function that's run in each thread */
void * sum(void* arg) {
len_array * a = (len_array*)arg;
unsigned len = a->len, i;
unsigned long long * data = (unsigned long long*)a->data;
unsigned long long acc = 0, cur;
unsigned long long * ret;
for (i = 0; i < len; i++) {
cur = data[i];
acc += cur;
}
ret = malloc(sizeof(unsigned long long));
*ret = acc;
return ret;
}
int main() {
printf("Sum [1..%d] using %d thread%s\n", LENGTH, NUM_THREADS, NUM_THREADS == 1?"":"s");
pthread_t threads[NUM_THREADS];
unsigned long long * data = malloc(sizeof(unsigned long long) * LENGTH);
len_array subdata[NUM_THREADS];
unsigned i, avg_per_thread = LENGTH / NUM_THREADS, extra = LENGTH % NUM_THREADS, index = 0;
for (i = 0; i < LENGTH; i++) {
data[i] = (unsigned long long)i;
}
index = 0;
for (i =0; i < NUM_THREADS; i++) {
subdata[i].data = &(data[index]);
subdata[i].len = avg_per_thread;
index += avg_per_thread;
if (extra > 0) {
subdata[i].len++;
extra--;
index++;
}
pthread_create(&(threads[i]), NULL, sum, (void*)&(subdata[i]));
}
unsigned long long res = 0, * ret;
for (i = 0; i < NUM_THREADS; i++) {
pthread_join(threads[i], (void**)&ret);
res += *(unsigned long long*)ret;
}
printf("%llu\n", res);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment