/* =============================================================================
 * 03_memory_consistency.c -- both threads read 0, and both are right
 * =============================================================================
 *
 * [Idea]
 *   Two threads, two variables, both starting at 0:
 *
 *       thread 1:  X = 1;  r1 = Y;
 *       thread 2:  Y = 1;  r2 = X;
 *
 *   Reason about every INTERLEAVING of those four operations and you will find
 *   outcomes (r1,r2) = (0,1), (1,0) and (1,1) -- but never (0,0). For (0,0),
 *   thread 1 would have to read Y before thread 2 wrote it AND thread 2 read X
 *   before thread 1 wrote it, which no sequential order allows.
 *
 *   Real hardware produces (0,0) anyway.
 *
 *   The reason is MEMORY CONSISTENCY. A core may buffer its store (in a store
 *   buffer) and let a later load pass it, and other cores may see the writes in
 *   a different order than the program wrote them. SEQUENTIAL CONSISTENCY -- the
 *   model your intuition uses, where all cores agree on one global order of all
 *   memory operations -- is NOT what most hardware gives you. x86-64 is close
 *   to it (TSO: stores can be reordered after loads); arm64 is deliberately
 *   WEAKER, and shows this effect readily.
 *
 *   This program runs the experiment millions of times and counts the outcomes.
 *
 * [What it answers]
 *   - Can (0,0) really happen? (count it and see)
 *   - What is sequential consistency, and why does hardware not provide it?
 *   - What makes it go away? (a memory barrier / an atomic with ordering)
 *
 * Build & run:    make run
 *
 * The (0,0) count varies enormously run to run and between machines; on a
 * strongly-ordered CPU it may be 0. Either outcome is reported honestly --
 * absence of the anomaly is not evidence of sequential consistency.
 * -----------------------------------------------------------------------------
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <stdatomic.h>
#include <sys/time.h>

#define ROUNDS 200000L

/* The two shared variables. `volatile` keeps the compiler from caching them in
 * registers or reordering the accesses -- we want to observe what the HARDWARE
 * does, not what the optimizer does. (volatile is NOT synchronization: it
 * provides no ordering guarantee between the two variables, which is exactly
 * the point of this demo.) */
static volatile int X, Y;
static volatile int r1, r2;

/* A barrier, written by hand: macOS provides no pthread_barrier_t.
 * Two threads arrive; both leave only when both have arrived. */
typedef struct {
    atomic_int count;
    atomic_int generation;
} barrier_t;

static barrier_t start_bar, end_bar;

static void barrier_init(barrier_t *b)
{
    atomic_init(&b->count, 0);
    atomic_init(&b->generation, 0);
}

static void barrier_wait(barrier_t *b, int nthreads)
{
    int gen = atomic_load(&b->generation);
    if (atomic_fetch_add(&b->count, 1) == nthreads - 1) {
        /* last to arrive: reset and open the gate */
        atomic_store(&b->count, 0);
        atomic_fetch_add(&b->generation, 1);
    } else {
        while (atomic_load(&b->generation) == gen)
            ; /* spin until the generation advances */
    }
}

/* Use a relaxed atomic for the ordering-free version so the COMPILER is not
 * the one reordering (that would prove nothing about hardware), while the
 * hardware remains free to do as it likes. */
static int use_barrier;

/* We need to reset X and Y between rounds, and observe r1/r2. The main thread
 * cannot do it without a third barrier, so instead each round's observation is
 * recorded by thread 1 after the end barrier -- see run(). */
static long outcome[2][2];      /* outcome[r1][r2] */

static void *observer(void *v)
{
    (void)v;
    for (long i = 0; i < ROUNDS; i++) {
        /* before the round: clear the variables */
        X = Y = 0;
        r1 = r2 = 0;
        barrier_wait(&start_bar, 3);
        barrier_wait(&end_bar, 3);
        /* after the round: both threads have finished their two operations */
        outcome[r1 & 1][r2 & 1]++;
    }
    return NULL;
}

/* With three participants the workers must also use 3 in their barriers. */
static void *thread1_3(void *v)
{
    (void)v;
    for (long i = 0; i < ROUNDS; i++) {
        barrier_wait(&start_bar, 3);
        X = 1;
        if (use_barrier) atomic_thread_fence(memory_order_seq_cst);
        r1 = Y;
        barrier_wait(&end_bar, 3);
    }
    return NULL;
}

static void *thread2_3(void *v)
{
    (void)v;
    for (long i = 0; i < ROUNDS; i++) {
        barrier_wait(&start_bar, 3);
        Y = 1;
        if (use_barrier) atomic_thread_fence(memory_order_seq_cst);
        r2 = X;
        barrier_wait(&end_bar, 3);
    }
    return NULL;
}

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

static double run(int with_barrier)
{
    use_barrier = with_barrier;
    memset(outcome, 0, sizeof(outcome));
    barrier_init(&start_bar);
    barrier_init(&end_bar);

    pthread_t t1, t2, ob;
    double t0 = now_ms();
    pthread_create(&ob, NULL, observer, NULL);
    pthread_create(&t1, NULL, thread1_3, NULL);
    pthread_create(&t2, NULL, thread2_3, NULL);
    pthread_join(ob, NULL);
    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    return now_ms() - t0;
}

static void report(const char *label, double ms)
{
    printf("  %s (%.0f ms, %ld rounds)\n", label, ms, ROUNDS);
    printf("    (r1,r2) = (1,1): %8ld\n", outcome[1][1]);
    printf("    (r1,r2) = (0,1): %8ld\n", outcome[0][1]);
    printf("    (r1,r2) = (1,0): %8ld\n", outcome[1][0]);
    printf("    (r1,r2) = (0,0): %8ld   <-- impossible under sequential "
           "consistency\n", outcome[0][0]);
}

int main(void)
{
    printf("thread 1:  X = 1;  r1 = Y;      thread 2:  Y = 1;  r2 = X;\n");
    printf("X and Y start at 0 each round. Under SEQUENTIAL CONSISTENCY the\n");
    printf("outcome (0,0) cannot occur: some write must precede both reads.\n\n");

    printf("== without any memory barrier ==\n");
    double ms_free = run(0);
    long anomalies = outcome[0][0];
    report("plain stores and loads", ms_free);

    printf("\n== with a seq_cst memory fence between the store and the load ==\n");
    double ms_fenced = run(1);
    long anomalies_fenced = outcome[0][0];
    report("atomic_thread_fence(memory_order_seq_cst)", ms_fenced);

    printf("\nObservations\n------------\n");
    if (anomalies > 0) {
        printf("- (0,0) occurred %ld times out of %ld rounds (%.4f%%). That\n",
               anomalies, ROUNDS, 100.0 * (double)anomalies / (double)ROUNDS);
        printf("  outcome is IMPOSSIBLE if you assume all cores see one global\n");
        printf("  order of memory operations. The hardware does not provide\n");
        printf("  that: each core buffered its store and let its load go ahead,\n");
        printf("  so both read the other's variable before either write became\n");
        printf("  visible. Your intuition about memory order is not a guarantee.\n");
    } else {
        printf("- (0,0) did NOT occur in %ld rounds on this run. That is not\n",
               ROUNDS);
        printf("  proof of sequential consistency -- the reordering window is\n");
        printf("  tiny and depends on the cores involved (on this machine the\n");
        printf("  scheduler may have placed both threads on cores that share a\n");
        printf("  store buffer, or simply never aligned the two operations).\n");
        printf("  The anomaly is permitted by the architecture whether or not it\n");
        printf("  appeared here, so code must not rely on its absence.\n");
    }
    printf("- With a seq_cst fence, (0,0) occurred %ld times: the fence forbids\n",
           anomalies_fenced);
    printf("  the store/load reordering, restoring the behaviour your reasoning\n");
    printf("  assumed. It costs time (%.0f ms vs %.0f ms here).\n",
           ms_fenced, ms_free);
    printf("- This is why you should NOT write your own synchronization out of\n");
    printf("  plain loads and stores. Use mutexes, semaphores, or atomics with\n");
    printf("  explicit ordering: they emit the right barriers for the platform.\n");
    printf("- `volatile` does NOT help. It stops the COMPILER caching a value,\n");
    printf("  but emits no barrier, so the HARDWARE may still reorder. volatile\n");
    printf("  is for device registers and signal flags, never for inter-thread\n");
    printf("  ordering.\n");
    return 0;
}
