/* =============================================================================
 * 01_badcnt.c -- two threads, one counter, missing updates
 * =============================================================================
 *
 * [Idea]
 *   The shortest broken concurrent program there is:
 *
 *       for (i = 0; i < niters; i++)
 *           cnt++;                       /@ cnt is a global, shared @/
 *
 *   Run it in two threads with niters each and the answer should be 2*niters.
 *   It is not. `cnt++` is not one operation -- it is LOAD, ADD, STORE (demo 03
 *   shows the actual instructions). If both threads load the same old value,
 *   both add one, and both store, then two increments produce ONE increase.
 *   The lost updates are invisible in the source and depend on the schedule.
 *
 *   This program measures the damage, then fixes it three ways -- a mutex, a
 *   semaphore, and an atomic variable -- and checks each gives exactly the
 *   right answer.
 *
 * [What it answers]
 *   - How many updates actually get lost, and does it vary?
 *   - What is a critical section, and what makes mutual exclusion enough?
 *   - How do a mutex, a semaphore and an atomic each enforce it?
 *
 * Build & run:    make run
 *
 * [IMPORTANT -- why this is built twice]
 *   `make run` runs this program compiled at -O0 AND at -O2, because the
 *   optimization level changes whether the race appears at all:
 *     -O0: the loop really loads, adds and stores `cnt` a million times, so
 *          threads interleave constantly and updates are lost in droves.
 *     -O2: the compiler notices the loop just adds NITERS to `cnt` and
 *          collapses it into ONE add. With a single operation per thread the
 *          window is tiny, so the result is usually (not always) correct.
 *   The -O2 result is NOT a fix: the variable is still shared and the single
 *   remaining read-modify-write is still not atomic (demo 03 shows this in the
 *   instructions). It is luck, and luck that changes with the compiler.
 *
 * The broken count differs every run (that is the nature of a race); every
 * fixed version is exactly right every run.
 * -----------------------------------------------------------------------------
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <stdatomic.h>
#include <sys/time.h>
#include "psem.h"

/* Set by the Makefile via -DOPTLEVEL=\"-O0\" / \"-O2\" so the output
   says which build produced it. */
#ifndef OPTLEVEL
#define OPTLEVEL "(unspecified)"
#endif

#define NTHREADS 4
#define NITERS   500000L           /* per thread */
#define EXPECTED ((long)NTHREADS * NITERS)

/* ---- the shared state, one variable per experiment ------------------------ */
static long            cnt_bad   = 0;   /* no synchronization at all      */
static long            cnt_mutex = 0;   /* protected by a mutex           */
static long            cnt_sem   = 0;   /* protected by a binary semaphore */
static atomic_long     cnt_atomic;      /* an atomic read-modify-write    */

static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static psem_t          sem;

static double now_ms(void)
{
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return tv.tv_sec * 1000.0 + tv.tv_usec / 1000.0;
}

/* ---- experiment 1: the race --------------------------------------------- */
static void *thread_bad(void *v)
{
    (void)v;
    for (long i = 0; i < NITERS; i++)
        cnt_bad++;                  /* LOAD, ADD, STORE -- interruptible */
    return NULL;
}

/* ---- experiment 2: a mutex --------------------------------------------- */
/* The three instructions become a CRITICAL SECTION: a region at most one
 * thread may be executing at a time. lock/unlock bracket it. */
static void *thread_mutex(void *v)
{
    (void)v;
    for (long i = 0; i < NITERS; i++) {
        pthread_mutex_lock(&mutex);
        cnt_mutex++;                /* critical section */
        pthread_mutex_unlock(&mutex);
    }
    return NULL;
}

/* ---- experiment 3: a binary semaphore ----------------------------------- */
/* A semaphore initialized to 1 is a lock: P waits for the single "permit" and
 * takes it, V gives it back. Identical effect, different primitive. */
static void *thread_sem(void *v)
{
    (void)v;
    for (long i = 0; i < NITERS; i++) {
        psem_P(&sem);
        cnt_sem++;                  /* critical section */
        psem_V(&sem);
    }
    return NULL;
}

/* ---- experiment 4: an atomic variable ---------------------------------- */
/* No lock at all: the hardware performs read-modify-write as ONE
 * uninterruptible operation, so there is no window to interleave. */
static void *thread_atomic(void *v)
{
    (void)v;
    for (long i = 0; i < NITERS; i++)
        atomic_fetch_add(&cnt_atomic, 1);
    return NULL;
}

/* Run `fn` in NTHREADS threads, join them, and report. */
static double run(const char *label, void *(*fn)(void *), long got)
{
    pthread_t tid[NTHREADS];
    double t0 = now_ms();
    for (int i = 0; i < NTHREADS; i++)
        pthread_create(&tid[i], NULL, fn, NULL);
    for (int i = 0; i < NTHREADS; i++)
        pthread_join(tid[i], NULL);
    double ms = now_ms() - t0;
    (void)label; (void)got;
    return ms;
}

static void report(const char *label, long got, double ms)
{
    long lost = EXPECTED - got;
    printf("  %-22s result %9ld / %9ld  %s", label, got, EXPECTED,
           got == EXPECTED ? "CORRECT" : "WRONG");
    if (lost != 0)
        printf("  (%ld updates lost, %.2f%%)", lost,
               100.0 * (double)lost / (double)EXPECTED);
    printf("   [%.0f ms]\n", ms);
}

int main(void)
{
    atomic_init(&cnt_atomic, 0);
    if (psem_init(&sem, 1) != 0) return 1;      /* 1 = a binary semaphore */

    printf("compiled at %s\n", OPTLEVEL);
    printf("%d threads x %ld increments each; the answer must be %ld\n",
           NTHREADS, NITERS, EXPECTED);
    printf("semaphore backend: %s\n\n", psem_backend());

    double ms;

    printf("== 1. no synchronization (a RACE) ==\n");
    ms = run("unsynchronized", thread_bad, cnt_bad);
    report("cnt++ (unprotected)", cnt_bad, ms);
    printf("     `cnt++` is LOAD, ADD, STORE. Two threads can load the same\n");
    printf("     old value, so two increments produce one increase.\n\n");

    printf("== 2. the three standard fixes ==\n");
    ms = run("mutex", thread_mutex, cnt_mutex);
    report("pthread_mutex", cnt_mutex, ms);
    ms = run("semaphore", thread_sem, cnt_sem);
    report("binary semaphore P/V", cnt_sem, ms);
    ms = run("atomic", thread_atomic, (long)atomic_load(&cnt_atomic));
    report("atomic_fetch_add", (long)atomic_load(&cnt_atomic), ms);

    printf("\nObservations\n------------\n");
    if (cnt_bad != EXPECTED) {
        printf("- The unprotected counter lost %ld of %ld updates (%.1f%%).\n",
               EXPECTED - cnt_bad, EXPECTED,
               100.0 * (double)(EXPECTED - cnt_bad) / (double)EXPECTED);
        printf("  Nothing in the source says 'cnt++ may be interrupted', but it may.\n");
    } else {
        printf("- The unprotected counter happened to come out RIGHT this time\n");
        printf("  (%ld). At -O2 the compiler collapses the whole loop into a\n", cnt_bad);
        printf("  single add, so each thread performs ONE read-modify-write and\n");
        printf("  the window to interleave is tiny. That is luck, not safety:\n");
        printf("  the variable is still shared and that one operation is still\n");
        printf("  not atomic. Compare the -O0 run above, and see demo 03.\n");
    }
    printf("- All three fixes gave EXACTLY %ld. A mutex and a binary semaphore\n",
           EXPECTED);
    printf("  both enforce mutual exclusion on the critical section; the atomic\n");
    printf("  instead makes the operation itself indivisible, with no lock.\n");
    printf("- The fixes are not free -- see demo 02 for the cost of each, and\n");
    printf("  note the broken version is the FASTEST and the most wrong.\n");
    printf("- Rerun this: the broken number changes, the fixed ones never do.\n");
    printf("  A race is a reasoning error, not a testing problem.\n");

    psem_destroy(&sem);
    return 0;
}
