/* Four threads share one job, then share one counter.
   First each thread adds up a quarter of 1..1000000 and main adds the parts.
   Then all four add 1 to the same counter 100000 times, taking turns with a
   mutex so no update is lost.
   Build it and run it:
     cc -pthread -o threads threads.c
     ./threads
*/
#include <pthread.h>
#include <stdio.h>

#define N 1000000L
#define THREADS 4
#define ADDS 100000

static long parts[THREADS];
static long counter = 0;
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

static void *add_quarter(void *arg) {
    long id = (long)arg;
    long from = id * (N / THREADS) + 1;
    long to = (id + 1) * (N / THREADS);
    long sum = 0;
    for (long i = from; i <= to; i++) sum += i;
    parts[id] = sum; /* each thread writes only its own slot */
    return NULL;
}

static void *count_up(void *arg) {
    (void)arg;
    for (int i = 0; i < ADDS; i++) {
        pthread_mutex_lock(&lock); /* one thread at a time past here */
        counter++;
        pthread_mutex_unlock(&lock);
    }
    return NULL;
}

int main(void) {
    pthread_t t[THREADS];
    for (long i = 0; i < THREADS; i++) pthread_create(&t[i], NULL, add_quarter, (void *)i);
    for (int i = 0; i < THREADS; i++) pthread_join(t[i], NULL); /* wait for all four */

    long total = 0;
    for (int i = 0; i < THREADS; i++) {
        printf("thread %d added up %ld\n", i, parts[i]);
        total += parts[i];
    }
    printf("total %ld, and the formula n(n+1)/2 says %ld\n", total, N * (N + 1) / 2);

    for (int i = 0; i < THREADS; i++) pthread_create(&t[i], NULL, count_up, NULL);
    for (int i = 0; i < THREADS; i++) pthread_join(t[i], NULL);
    printf("shared counter %ld, expected %d\n", counter, THREADS * ADDS);
    return 0;
}
