/* =============================================================================
 * 02_false_sharing.c -- threads that share nothing, and fight anyway
 * =============================================================================
 *
 * [Idea]
 *   Lecture 22's conclusion was "give each thread its own variable". So do it:
 *
 *       long counter[NTHREADS];          /@ thread i uses counter[i] only @/
 *
 *   No thread ever touches another's element. There is no race, no lock, and
 *   the answer is always right. And it can be many times SLOWER than the
 *   version where each counter sits on its own cache line.
 *
 *   The reason is that the unit of coherence is not the variable but the CACHE
 *   LINE (128 bytes on this machine). Eight adjacent `long`s fit in one line,
 *   so all eight threads are writing THE SAME LINE. Cache coherence requires a
 *   core to hold a line EXCLUSIVELY before writing it, so the line ping-pongs
 *   between the cores' caches -- one transfer per write. The threads are
 *   logically independent and physically in contention.
 *
 *   That is FALSE SHARING: the sharing is an artefact of memory layout, not of
 *   the program's logic. The fix is padding -- give each counter its own line.
 *
 * [What it answers]
 *   - How much does false sharing actually cost? (measured here)
 *   - Why does padding fix it, and how much padding?
 *   - How do I know my machine's cache-line size?
 *
 * Build & run:    make run
 *
 * Timings vary run to run; the ratio is large and stable.
 * -----------------------------------------------------------------------------
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <sys/time.h>
#ifdef __APPLE__
#include <sys/sysctl.h>
#endif

#define NTHREADS 8
#define NITERS   20000000L      /* increments per thread */

/* ---- layout A: packed. Adjacent longs -> the SAME cache line. ------------ */
static long packed[NTHREADS];

/* ---- layout B: padded. Each counter gets a whole line to itself. --------- */
#define LINE 128                /* this machine's cache line; see output */
typedef struct { long value; char pad[LINE - sizeof(long)]; } padded_t;
static padded_t padded[NTHREADS];

/* ---- layout C: the real fix -- accumulate in a register, publish once. --- */
static padded_t final_[NTHREADS];

static int thread_id[NTHREADS];

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

/* Each worker hammers ITS OWN counter. No thread touches another's. */
static void *w_packed(void *vargp)
{
    int id = *(int *)vargp;
    for (long i = 0; i < NITERS; i++) {
        packed[id]++;                   /* same line as its neighbours */
        /* [C tip] Without this barrier -O2 collapses the loop into a single
           `packed[id] += NITERS`, so BOTH layouts measured 0 ms and the
           comparison was meaningless. The clobber forces a real load-add-store
           each iteration, which is what makes the cache line travel. */
        __asm__ volatile("" ::: "memory");
    }
    return NULL;
}

static void *w_padded(void *vargp)
{
    int id = *(int *)vargp;
    for (long i = 0; i < NITERS; i++) {
        padded[id].value++;             /* its own line */
        __asm__ volatile("" ::: "memory");   /* same barrier, fair comparison */
    }
    return NULL;
}

static void *w_register(void *vargp)
{
    int id = *(int *)vargp;
    long local = 0;
    for (long i = 0; i < NITERS; i++) {
        local++;
        /* Keep the loop real without memory traffic (Lectures 9, 15, 22). */
        __asm__ volatile("" : "+r"(local));
    }
    final_[id].value = local;           /* one store, at the end */
    return NULL;
}

static double run(void *(*fn)(void *))
{
    pthread_t tid[NTHREADS];
    memset(packed, 0, sizeof(packed));
    memset(padded, 0, sizeof(padded));
    memset(final_, 0, sizeof(final_));

    double t0 = now_ms();
    for (int i = 0; i < NTHREADS; i++) {
        thread_id[i] = i;
        pthread_create(&tid[i], NULL, fn, &thread_id[i]);
    }
    for (int i = 0; i < NTHREADS; i++)
        pthread_join(tid[i], NULL);
    return now_ms() - t0;
}

static long cache_line_size(void)
{
#ifdef __APPLE__
    long v = 0; size_t len = sizeof(v);
    if (sysctlbyname("hw.cachelinesize", &v, &len, NULL, 0) == 0)
        return v;
#endif
    return 0;
}

int main(void)
{
    long line = cache_line_size();
    printf("%d threads x %ld increments of their OWN counter\n", NTHREADS, NITERS);
    if (line)
        printf("this machine's cache line: %ld bytes "
               "(so %ld longs share one line)\n", line, line / (long)sizeof(long));
    printf("padding used in layout B: %d bytes per counter\n\n", LINE);

    double ms_packed  = run(w_packed);
    double ms_padded  = run(w_padded);
    double ms_reg     = run(w_register);

    /* All three are CORRECT -- check it, so nobody suspects a trick. */
    int ok = 1;
    for (int i = 0; i < NTHREADS; i++)
        if (final_[i].value != NITERS) ok = 0;

    printf("  %-42s %10s %10s\n", "layout", "time(ms)", "vs packed");
    printf("  %-42s %10s %10s\n",
           "------------------------------------------", "--------", "---------");
    printf("  %-42s %10.0f %9s\n",
           "A: long counter[8]  (packed, one line)", ms_packed, "1.00x");
    printf("  %-42s %10.0f %8.2fx\n",
           "B: struct{long;char pad[120];} counter[8]", ms_padded,
           ms_packed / ms_padded);
    printf("  %-42s %10.0f %8.2fx\n",
           "C: local register, one store at the end", ms_reg,
           ms_packed / ms_reg);
    printf("\n  all layouts computed the correct per-thread total: %s\n",
           ok ? "yes" : "NO");

    printf("\nObservations\n------------\n");
    printf("- Layout A and layout B are the SAME program logically. No thread\n");
    printf("  reads or writes another thread's counter in either. Yet B is\n");
    printf("  %.2fx faster, purely because of where the counters sit in memory.\n",
           ms_packed / ms_padded);
    printf("- The cause is the CACHE LINE (%ld bytes here). In layout A all 8\n",
           line ? line : LINE);
    printf("  counters live in one line, and a core must own a line EXCLUSIVELY\n");
    printf("  to write it, so the line bounces between the 8 cores' caches --\n");
    printf("  one coherence transfer per increment. Independent threads, fully\n");
    printf("  serialized by the memory system.\n");
    printf("- Padding each counter to its own line removes the interference\n");
    printf("  entirely: the threads stop interacting because their lines differ.\n");
    printf("- Layout C is better still (%.2fx): keep the running value in a\n",
           ms_packed / ms_reg);
    printf("  REGISTER and store once at the end. Then there is no repeated\n");
    printf("  memory traffic to be coherent about at all. Prefer this; use\n");
    printf("  padding when a value genuinely must live in memory.\n");
    printf("- Moral: 'each thread has its own variable' is not enough. Each\n");
    printf("  thread needs its own CACHE LINE. This is why you will see\n");
    printf("  alignas(64)/alignas(128) and pad[] fields in real concurrent code.\n");
    return 0;
}
