/* =============================================================================
 * 02_sync_cost.c -- what each synchronization primitive actually costs
 * =============================================================================
 *
 * [Idea]
 *   Mutual exclusion is not free, and the primitives differ by an order of
 *   magnitude. Worse, their cost depends on CONTENTION: a lock nobody else
 *   wants is cheap, and the same lock with four threads fighting over it is
 *   not. This demo measures the same total work five ways, at 1 thread
 *   (uncontended) and at 4 (contended), and reports nanoseconds per operation.
 *
 *   The five:
 *     unsynchronized      the baseline -- fast and WRONG (demo 01)
 *     atomic              one indivisible hardware read-modify-write
 *     mutex               pthread_mutex_lock / unlock
 *     semaphore           P / V on a binary semaphore
 *     private + combine   each thread counts in its OWN variable, summed once
 *                         at the end -- correct AND unsynchronized in the loop
 *
 * [The lesson]
 *   The last one is the point. The cheapest synchronization is the
 *   synchronization you do not do: restructure so threads do not share the hot
 *   variable at all, then combine their results once. Lecture 24 measures this
 *   again from the parallelism side (and finds the cache-line trap in it).
 *
 * Build & run:    make run
 *
 * Timings vary run to run; the ORDER and rough ratios are stable.
 * -----------------------------------------------------------------------------
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <stdatomic.h>
#include <sys/time.h>
#include "psem.h"

#define MAXTHREADS 8
#define TOTAL_OPS  1000000L        /* total increments, split across threads */

static long            shared_plain = 0;
static atomic_long     shared_atomic;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static psem_t          sem;

/* Per-thread private counters, generously spaced so two threads never share a
 * cache line (Lecture 24 explains why 128 bytes, and what happens without it). */
typedef struct { long value; char pad[128 - sizeof(long)]; } padded_long;
static padded_long private_count[MAXTHREADS];

static long ops_per_thread;        /* set from TOTAL_OPS / nthreads */

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

static void *w_plain(void *v)
{
    (void)v;
    for (long i = 0; i < ops_per_thread; i++) {
        shared_plain++;
        /* [C tip] Without this barrier, -O2 collapses the whole loop into
           `shared_plain += ops_per_thread` -- one add instead of a million --
           and the "measurement" would be of a loop that does not exist. The
           empty asm with a "memory" clobber tells the compiler that memory may
           have changed, forcing a real load-add-store each iteration. Same
           technique as Lectures 9 and 15. */
        __asm__ volatile("" ::: "memory");
    }
    return NULL;
}
static void *w_atomic(void *v)
{
    (void)v;
    for (long i = 0; i < ops_per_thread; i++) atomic_fetch_add(&shared_atomic, 1);
    return NULL;
}
static void *w_mutex(void *v)
{
    (void)v;
    for (long i = 0; i < ops_per_thread; i++) {
        pthread_mutex_lock(&mutex);
        shared_plain++;
        pthread_mutex_unlock(&mutex);
    }
    return NULL;
}
static void *w_sem(void *v)
{
    (void)v;
    for (long i = 0; i < ops_per_thread; i++) {
        psem_P(&sem);
        shared_plain++;
        psem_V(&sem);
    }
    return NULL;
}
static void *w_private(void *vargp)
{
    int id = *(int *)vargp;
    /* [C tip] accumulate in a LOCAL, then publish once. Touching
       private_count[id].value every iteration would still be a memory write
       other cores could contend for; a register-resident local cannot be. */
    long local = 0;
    for (long i = 0; i < ops_per_thread; i++) {
        local++;
        /* Keep the loop real without forcing memory traffic: this tells the
           compiler `local` is read and written by something it cannot see, so
           it must iterate -- but `local` stays in a REGISTER, which is exactly
           the property being measured. (A "memory" clobber here would add the
           very memory traffic we are trying to avoid.) */
        __asm__ volatile("" : "+r"(local));
    }
    private_count[id].value = local;
    return NULL;
}

/* Time one scheme with `n` threads; returns nanoseconds per operation. */
static double measure(void *(*fn)(void *), int n)
{
    pthread_t tid[MAXTHREADS];
    int ids[MAXTHREADS];
    ops_per_thread = TOTAL_OPS / n;

    shared_plain = 0;
    atomic_init(&shared_atomic, 0);
    memset(private_count, 0, sizeof(private_count));

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

    return ms * 1e6 / (double)(ops_per_thread * n);   /* ns per operation */
}

int main(void)
{
    if (psem_init(&sem, 1) != 0) return 1;

    printf("cost of one increment, %ld operations total, in ns/op\n", TOTAL_OPS);
    printf("semaphore backend: %s\n\n", psem_backend());

    printf("  %-20s %12s %12s %10s\n",
           "scheme", "1 thread", "4 threads", "correct?");
    printf("  %-20s %12s %12s %10s\n",
           "--------------------", "------------", "------------", "--------");

    struct { const char *name; void *(*fn)(void *); const char *correct; } t[] = {
        { "unsynchronized",   w_plain,   "NO"  },
        { "atomic",           w_atomic,  "yes" },
        { "mutex",            w_mutex,   "yes" },
        { "semaphore P/V",    w_sem,     "yes" },
        { "private + combine", w_private, "yes" },
    };

    double one[5], four[5];
    for (int i = 0; i < 5; i++) {
        one[i]  = measure(t[i].fn, 1);
        four[i] = measure(t[i].fn, 4);
        printf("  %-20s %10.2f   %10.2f   %10s\n",
               t[i].name, one[i], four[i], t[i].correct);
    }

    printf("\nObservations\n------------\n");
    printf("- Uncontended (1 thread), private+combine is cheapest at %.2f ns/op;\n",
           one[4]);
    printf("  an atomic (%.2f) costs about the same as an unsynchronized shared\n",
           one[1]);
    printf("  increment (%.2f) because both are one read-modify-write with no\n",
           one[0]);
    printf("  other thread to interfere; a mutex adds a little (%.2f).\n", one[2]);
    printf("- Contended (4 threads) the picture changes completely: every thread\n");
    printf("  now fights for the same cache line and the same lock, so the\n");
    printf("  SHARED schemes get slower PER OPERATION even though more cores are\n");
    printf("  working (atomic %.2f, mutex %.2f, semaphore %.2f ns/op).\n",
           four[1], four[2], four[3]);
    printf("  Adding cores made the shared counter WORSE, not better.\n");
    printf("- private+combine is the only CORRECT scheme that gets faster with\n");
    printf("  more threads (%.2f -> %.2f ns/op): there is nothing to contend for,\n",
           one[4], four[4]);
    printf("  so it is the only one that actually scales.\n");
    printf("- So the ranking is not 'which lock is fastest' but 'can I avoid\n");
    printf("  sharing at all'. Lock only what must be shared, and keep the\n");
    printf("  critical section as short as possible.\n");
    printf("- Caveat 1: the unsynchronized column is WRONG (demo 01) and is here\n");
    printf("  only as a speed-of-light baseline.\n");
    printf("- Caveat 2: the SEMAPHORE numbers are a macOS artefact, not a\n");
    printf("  property of semaphores. macOS has no working sem_init(), so psem\n");
    printf("  uses NAMED semaphores, which are kernel objects -- every P and V\n");
    printf("  is a system call. A pthread_mutex has a user-space fast path and\n");
    printf("  needs no syscall when uncontended, hence the ~100x gap. On Linux,\n");
    printf("  sem_wait on an unnamed semaphore is a futex with a user-space fast\n");
    printf("  path too, and would land near the mutex. Compare mutex vs atomic\n");
    printf("  here; do not conclude 'semaphores are slow'.\n");

    psem_destroy(&sem);
    return 0;
}
