// Class 24, section 1: twelve threads adding every number below N to one
// shared sum, by hand. On bfh103, 11/17, built without -O2: a sum well short
// of 4999999950000000, different each run; -fsanitize=thread names line 22.
#include <stdio.h>
#include <pthread.h>

#define N 100000000L
#define THREADS 12

// one thread's part of the count
struct share {
    long start;     // the first number it counts
    long end;       // one past its last
    long * sum;     // the sum every thread adds to
};

// adds every number from s->start up to s->end into *s->sum
void * count_share(void * arg) {
    struct share * s = (struct share *) arg;
    for (long i = s->start; i < s->end; i++) {
        *s->sum += i;
    }
    return NULL;
}

int main() {
    long sum = 0;
    pthread_t threads[THREADS];
    struct share shares[THREADS];
    for (int t = 0; t < THREADS; t++) {
        shares[t].start = t * N / THREADS;
        shares[t].end = (t + 1) * N / THREADS;
        shares[t].sum = &sum;
        pthread_create(&threads[t], NULL, count_share, &shares[t]);
    }
    for (int t = 0; t < THREADS; t++) {
        pthread_join(threads[t], NULL);
    }
    printf("sum %ld, want %ld\n", sum, N * (N - 1) / 2);
}
