//_____________________________________________________________________________
//      thread.c, by Stanko Juzbasic
//      this is test/tutorial code for checking/demonstrating basic thread work
//      it takes array length as user argument, gets number of CPUs from system
//      it spawns threads, does some test work on the arrays, then returns
//      on thread joining results are being interpreted and printed
//      some of this paradigm can be useful in computer music number crunching
//		/* commented for studying convenience */
//      compile: cc -o thread1 thread1.c -lpthread
//      or     : cc -O2 -std=c11 -pthread thread.c -o thread
//_____________________________________________________________________________

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <pthread.h>
#include <sys/sysctl.h>

static int nThreads;
static const char *c = "Computing in thread ";
static size_t size;          // number of elements per row
static int **data = NULL;    // global array
static bool noprint = false;

// ------------------------------------------------------------------
// OSX/BSD specific: get number of logical CPUs
static int getCPUnum(void)
{
    int numCPU = 1;          // default
    int mib[2] = {CTL_HW, HW_AVAILCPU};
    size_t len   = sizeof(numCPU);
    if (sysctl(mib, 2, &numCPU, &len, NULL, 0) == -1)
        perror("sysctl");
    return numCPU > 0 ? numCPU : 1;
}

// ------------------------------------------------------------------
// Thread routine
static void *work(void *arg)
{
    int tid = *(int *)arg;
    printf("\t%s%d\n", c, tid);

    if (data) {
        for (size_t i = 0; i < size; ++i)
            data[tid][i] = 1 + (int)(i % (tid + 2));
    } else
        printf("\t\tdata = NULL\n");

    int *ret = malloc(sizeof(*ret));
    if (!ret) { perror("malloc"); exit(EXIT_FAILURE); }
    *ret = 1;
    return ret;
}

// ------------------------------------------------------------------
// Create threads, wait for them and aggregate the result
static int spin_threads(int num)
{
    pthread_t      *threads = calloc(num, sizeof(*threads));
    int            *tids    = calloc(num, sizeof(*tids));
    void           *result;
    int             thread_sum = 0;
    size_t          j;

    /* Allocate the shared array */
    data       = calloc(num, sizeof(*data));
    int *work_sum = calloc(size, sizeof(*work_sum));

    /* Launch the threads */
    for (int i = 0; i < num; ++i) {
        data[i]   = calloc(size, sizeof(**data));
        tids[i]   = i;
        printf("Spawning thread %d\n", i);
        if (pthread_create(&threads[i], NULL, work, &tids[i]) != 0) {
            perror("pthread_create");
            exit(EXIT_FAILURE);
        }
    }

    /* Join them */
    for (int i = 0; i < num; ++i) {
        if (pthread_join(threads[i], &result) != 0) {
            perror("pthread_join");
            exit(EXIT_FAILURE);
        }
        thread_sum += *(int *)result;
        free(result);          // <‑‑ no memory leak !!
    }

    /* Print the matrix and row sums */
    for (int i = 0; i < num; ++i) {
        for (j = 0; j < size; ++j) {
            work_sum[j] += data[i][j];
            if (!noprint)
                printf("%d ", data[i][j]);
        }
        if (!noprint) puts("");
    }

    printf("_________________________\n");
    if (!noprint) {
        for (j = 0; j < size; ++j)
            printf("%d ", work_sum[j]);
        puts("");
    }

    /* Clean up */
    for (int i = 0; i < num; ++i)
        free(data[i]);
    free(data);
    free(threads);
    free(tids);
    free(work_sum);

    return thread_sum;
}

// ------------------------------------------------------------------
int main(int argc, const char *argv[])
{
    char buf[16] = {0};

    printf("\n-------- THREAD DEMO --------\n");

    if (argc > 1 && strcmp(argv[1], "-n") == 0)
        noprint = true;

    printf("\tEnter buffer length: ");
    if (!fgets(buf, sizeof buf, stdin)) {
        perror("fgets");
        return EXIT_FAILURE;
    }
    size = strtoul(buf, NULL, 10);
    if (size > 31250000) size = 31250000;

    nThreads = getCPUnum();
    printf("\nNumber of CPUs: %d\n", nThreads);

    int sum = spin_threads(nThreads);
    printf("Joined %d threads\n\n", sum);

    return EXIT_SUCCESS;
}
