/* =============================================================================
 * 04_unintended_sharing.c -- the bug that every first thread program has
 * =============================================================================
 *
 * [Idea]
 *   pthread_create takes ONE void* argument, so the obvious thing is to pass a
 *   pointer to the loop variable:
 *
 *       for (int i = 0; i < N; i++)
 *           pthread_create(&tid, NULL, worker, &i);      /@ WRONG @/
 *
 *   Every thread receives the SAME address. The main thread keeps incrementing
 *   that variable while the new threads are still starting up, so a thread that
 *   reads *p a moment later sees whatever `i` has reached by then -- not the
 *   value it was "given". Threads end up with duplicate ids, some ids are never
 *   seen at all, and the bug is timing-dependent, so it may hide on your
 *   machine and appear on the grader's.
 *
 *   This is UNINTENDED SHARING: the variable was never meant to be shared, but
 *   threads share the address space by default, so passing its address shares
 *   it. The fix is to give each thread its own copy.
 *
 * [What it answers]
 *   - Why is passing &i to every thread wrong?
 *   - What does the damage actually look like? (counted here, not asserted)
 *   - What are the two standard fixes?
 *
 * Build & run:    make run
 *
 * The exact duplicate/missing counts vary run to run -- that is the nature of
 * a race. The BROKEN version is essentially never correct; the FIXED version
 * is always perfect.
 * -----------------------------------------------------------------------------
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>

#define N 16        /* threads per experiment */

/* Each thread records the id it believes it was given, in its own slot, so
 * recording itself is race-free and only the ARGUMENT passing is under test. */
static int seen_broken[N];
static int seen_fixed[N];
static pthread_mutex_t slot_mutex = PTHREAD_MUTEX_INITIALIZER;
static int next_slot = 0;

/* Claim the next output slot (protected, so the bookkeeping is not itself racy). */
static int claim_slot(void)
{
    pthread_mutex_lock(&slot_mutex);
    int s = next_slot++;
    pthread_mutex_unlock(&slot_mutex);
    return s;
}

/* ---- the BROKEN worker: dereferences a pointer into main's loop variable --- */
static void *worker_broken(void *vargp)
{
    /* A short pause stands in for the real startup latency of a thread. It
       makes the race reliable instead of merely likely -- the bug is the same
       either way, we are only making it visible. */
    usleep(1000);
    int my_id = *((int *)vargp);        /* <-- reads main's `i`, whatever it is NOW */
    int slot = claim_slot();
    if (slot < N) seen_broken[slot] = my_id;
    return NULL;
}

/* ---- the FIXED worker: owns its argument --------------------------------- */
static void *worker_fixed(void *vargp)
{
    usleep(1000);
    int my_id = *((int *)vargp);        /* our OWN copy; nobody else can touch it */
    free(vargp);                        /* we were given it; we release it */
    int slot = claim_slot();
    if (slot < N) seen_fixed[slot] = my_id;
    return NULL;
}

/* Count duplicates and missing values in an array that SHOULD be a
 * permutation of 0..N-1. */
static void analyze(const char *label, const int *seen)
{
    /* Count how often each value 0..N-1 was received, and separately how many
       threads received something outside that range (i.e. i == N, the value the
       loop variable holds once main's loop has finished). */
    int count[N];
    memset(count, 0, sizeof(count));
    int out_of_range = 0;
    for (int i = 0; i < N; i++) {
        if (seen[i] >= 0 && seen[i] < N) count[seen[i]]++;
        else out_of_range++;
    }

    int missing = 0, distinct = 0, repeated_threads = 0;
    for (int v = 0; v < N; v++) {
        if (count[v] == 0) missing++;
        if (count[v] >= 1) distinct++;
        if (count[v] > 1)  repeated_threads += count[v] - 1;   /* extra copies */
    }
    if (out_of_range) distinct++;            /* the out-of-range value counts too */

    printf("  %-8s ids received:", label);
    for (int i = 0; i < N; i++) printf(" %d", seen[i]);
    printf("\n");
    printf("  %-8s %d thread(s) received %d DISTINCT value(s); "
           "%d of the %d expected ids never arrived\n", "",
           N, distinct, missing, N);
    if (out_of_range)
        printf("  %-8s %d thread(s) read a value outside 0..%d "
               "(main's loop had already finished, so i == %d)\n", "",
               out_of_range, N - 1, N);
    if (repeated_threads)
        printf("  %-8s %d thread(s) duplicated a value another thread also got\n",
               "", repeated_threads);
    printf("  %-8s => %s\n", "",
           (missing == 0 && out_of_range == 0 && repeated_threads == 0)
               ? "a correct permutation of 0..N-1"
               : "CORRUPT: threads did not get the ids they were 'given'");
}

int main(void)
{
    pthread_t tid[N];

    /* ---- experiment 1: the broken way ---------------------------------- */
    printf("== 1. BROKEN: pthread_create(..., &i) -- every thread gets ONE address ==\n");
    for (int i = 0; i < N; i++) seen_broken[i] = -1;
    next_slot = 0;
    int i;
    for (i = 0; i < N; i++)
        pthread_create(&tid[i], NULL, worker_broken, &i);   /* the bug */
    for (int j = 0; j < N; j++)
        pthread_join(tid[j], NULL);
    analyze("broken", seen_broken);

    /* ---- experiment 2: the fix ----------------------------------------- */
    printf("\n== 2. FIXED: each thread gets its own malloc'd copy ==\n");
    for (int k = 0; k < N; k++) seen_fixed[k] = -1;
    next_slot = 0;
    for (int k = 0; k < N; k++) {
        int *argp = malloc(sizeof(int));    /* one allocation per thread */
        *argp = k;                          /* filled BEFORE the thread starts */
        pthread_create(&tid[k], NULL, worker_fixed, argp);
    }
    for (int k = 0; k < N; k++)
        pthread_join(tid[k], NULL);
    analyze("fixed", seen_fixed);

    printf("\nObservations\n------------\n");
    printf("- The broken version passed one ADDRESS to all %d threads. By the\n", N);
    printf("  time they dereferenced it, main had moved on, so most of them\n");
    printf("  read the same late value: duplicates, and ids never delivered.\n");
    printf("- The fixed version gave each thread private memory, filled in\n");
    printf("  before the thread was created and freed by the thread itself.\n");
    printf("  It is a correct permutation every single run.\n");
    printf("- Threads share the address space BY DEFAULT. Sharing is therefore\n");
    printf("  the thing you must argue for, not against: pass a copy unless you\n");
    printf("  deliberately want sharing (and then you need a lock -- L22).\n");
    printf("- The counts above change from run to run. A race is not a bug you\n");
    printf("  can test away; it is a bug you must reason away.\n");
    return 0;
}
