/* =============================================================================
 * 02_readers_writers.c -- when a mutex is too strict
 * =============================================================================
 *
 * [Idea]
 *   Many threads read a shared structure; a few occasionally write it. A plain
 *   mutex works but is needlessly strict: it lets only ONE reader in at a time,
 *   although readers do not interfere with each other at all. The correct rule:
 *
 *       any number of READERS may hold the lock together
 *       a WRITER must hold it alone (no readers, no other writer)
 *
 *   That is a READERS/WRITERS lock, pthread_rwlock_t. This demo measures the
 *   difference: the same read-heavy workload under a mutex and under an
 *   rwlock, and counts the maximum number of readers that were ever inside
 *   the critical section simultaneously -- which is the point, made visible.
 *
 * [What it answers]
 *   - What does a readers/writers lock allow that a mutex does not?
 *   - How much does it actually buy on a read-heavy workload?
 *   - Why does this design risk STARVATION?
 *
 * Build & run:    make run
 *
 * Timings vary run to run; the concurrency counts and the direction of the
 * speedup are stable.
 * -----------------------------------------------------------------------------
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <stdatomic.h>
#include <unistd.h>
#include <sys/time.h>

#define NREADERS  8
#define NWRITERS  2
#define NREADS    20000L        /* per reader thread  */
#define NWRITES   200L          /* per writer thread  */
#define DATASIZE  64

/* The shared structure. Its invariant: every element holds the same value, so
 * a reader that sees a mixture has observed a half-finished write. */
static long data[DATASIZE];

static pthread_mutex_t  mutex  = PTHREAD_MUTEX_INITIALIZER;
static pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER;

/* Instrumentation: how many readers are inside right now, and the most ever. */
static atomic_int readers_inside = 0;
static atomic_int max_readers_inside = 0;
static atomic_long torn_reads = 0;      /* invariant violations seen */

static int use_rwlock;                  /* which scheme this run is testing */
static int read_passes = 1;             /* critical-section length knob   */

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

/* Read the structure and check its invariant, `passes` times over.
 * `passes` is the knob that sets how LONG the critical section is -- the
 * variable that decides whether an rwlock pays for itself. */
static void read_data(int passes)
{
    int inside = atomic_fetch_add(&readers_inside, 1) + 1;
    /* Record the high-water mark of concurrent readers. */
    int prev = atomic_load(&max_readers_inside);
    while (inside > prev &&
           !atomic_compare_exchange_weak(&max_readers_inside, &prev, inside))
        ; /* retry until we have published our value or someone published more */

    for (int p = 0; p < passes; p++) {
        long first = data[0];
        for (int i = 1; i < DATASIZE; i++)
            if (data[i] != first) { atomic_fetch_add(&torn_reads, 1); break; }
    }

    atomic_fetch_sub(&readers_inside, 1);
}

static void write_data(long v)
{
    /* Deliberately not instantaneous, so a torn read would be easy to catch
       if the locking were wrong. */
    for (int i = 0; i < DATASIZE; i++)
        data[i] = v;
}

static void *reader(void *v)
{
    (void)v;
    for (long i = 0; i < NREADS; i++) {
        if (use_rwlock) {
            pthread_rwlock_rdlock(&rwlock);     /* SHARED: others may join */
            read_data(read_passes);
            pthread_rwlock_unlock(&rwlock);
        } else {
            pthread_mutex_lock(&mutex);         /* EXCLUSIVE: one at a time */
            read_data(read_passes);
            pthread_mutex_unlock(&mutex);
        }
    }
    return NULL;
}

static void *writer(void *v)
{
    (void)v;
    for (long i = 0; i < NWRITES; i++) {
        if (use_rwlock) {
            pthread_rwlock_wrlock(&rwlock);     /* EXCLUSIVE */
            write_data(i);
            pthread_rwlock_unlock(&rwlock);
        } else {
            pthread_mutex_lock(&mutex);
            write_data(i);
            pthread_mutex_unlock(&mutex);
        }
        usleep(100);                            /* writers are occasional */
    }
    return NULL;
}

/* Run the whole workload under one scheme; return elapsed ms. */
static double run(int rwlock_mode, int passes, int *max_readers, long *torn)
{
    pthread_t rtid[NREADERS], wtid[NWRITERS];
    use_rwlock = rwlock_mode;
    read_passes = passes;
    atomic_store(&readers_inside, 0);
    atomic_store(&max_readers_inside, 0);
    atomic_store(&torn_reads, 0);
    memset(data, 0, sizeof(data));

    double t0 = now_ms();
    for (int i = 0; i < NREADERS; i++) pthread_create(&rtid[i], NULL, reader, NULL);
    for (int i = 0; i < NWRITERS; i++) pthread_create(&wtid[i], NULL, writer, NULL);
    for (int i = 0; i < NREADERS; i++) pthread_join(rtid[i], NULL);
    for (int i = 0; i < NWRITERS; i++) pthread_join(wtid[i], NULL);
    double ms = now_ms() - t0;

    *max_readers = atomic_load(&max_readers_inside);
    *torn        = atomic_load(&torn_reads);
    return ms;
}

int main(void)
{
    printf("%d readers x %ld reads, %d writers x %ld writes, %d-element structure\n\n",
           NREADERS, NREADS, NWRITERS, NWRITES, DATASIZE);

    /* The decisive variable is how much WORK happens inside the lock. An
       rwlock allows concurrency but costs more per acquisition than a mutex,
       so it only pays once the critical section is long enough to amortize
       that cost. We therefore measure both regimes. */
    const int passes[] = { 1, 100 };
    const char *label[] = { "SHORT (1 pass over 64 elements)",
                            "LONG  (100 passes over 64 elements)" };

    double sm[2], sr[2];
    int    mxm[2], mxr[2];
    long   tm[2], tr[2];

    for (int k = 0; k < 2; k++) {
        sm[k] = run(0, passes[k], &mxm[k], &tm[k]);
        sr[k] = run(1, passes[k], &mxr[k], &tr[k]);
    }

    for (int k = 0; k < 2; k++) {
        printf("  critical section: %s\n", label[k]);
        printf("    %-22s %10s %18s %12s\n",
               "scheme", "elapsed", "max readers inside", "torn reads");
        printf("    %-22s %10s %18s %12s\n",
               "----------------------", "----------", "------------------",
               "------------");
        printf("    %-22s %8.0f ms %18d %12ld\n",
               "pthread_mutex", sm[k], mxm[k], tm[k]);
        printf("    %-22s %8.0f ms %18d %12ld\n",
               "pthread_rwlock", sr[k], mxr[k], tr[k]);
        printf("    rwlock vs mutex: %.2fx  (%s)\n\n", sm[k] / sr[k],
               sr[k] < sm[k] ? "rwlock FASTER" : "rwlock SLOWER");
    }

    printf("Observations\n------------\n");
    printf("- The rwlock really does admit readers concurrently: up to %d were\n",
           mxr[1] > mxr[0] ? mxr[1] : mxr[0]);
    printf("  inside together, where the mutex never allowed more than %d.\n",
           mxm[0] > mxm[1] ? mxm[0] : mxm[1]);
    printf("  So the mechanism works exactly as advertised.\n");
    printf("- But concurrency is not the same as speed. With a SHORT critical\n");
    printf("  section the rwlock was %.2fx the mutex's time -- i.e. %s --\n",
           sm[0] / sr[0], sr[0] < sm[0] ? "faster" : "SLOWER");
    printf("  because an rwlock must atomically track a reader COUNT, and that\n");
    printf("  bookkeeping is itself contended. When the work inside the lock is\n");
    printf("  a few hundred nanoseconds, the overhead dominates the benefit.\n");
    printf("- With a LONG critical section the picture %s: %.2fx.\n",
           sr[1] < sm[1] ? "reverses, as theory predicts" : "stays the same",
           sm[1] / sr[1]);
    printf("  The longer readers stay inside, the more there is to overlap and\n");
    printf("  the better the rwlock's fixed cost is amortized.\n");
    printf("- Neither scheme produced a single torn read (%ld, %ld, %ld, %ld):\n",
           tm[0], tr[0], tm[1], tr[1]);
    printf("  writers always had exclusive access, so no reader ever saw a\n");
    printf("  half-written structure. Correctness was never traded away.\n");
    printf("- STARVATION is the hazard. If readers keep arriving while a writer\n");
    printf("  waits, a reader-preferring implementation may never let the writer\n");
    printf("  in. Favouring writers starves readers instead. Real\n");
    printf("  implementations pick a policy; neither is 'fair' by default, so\n");
    printf("  do not assume one.\n");
    printf("- So the rule is NOT 'reads dominate -> use an rwlock'. It is:\n");
    printf("  reads dominate AND the critical section is long enough to pay for\n");
    printf("  the extra bookkeeping. Measure; do not assume.\n");
    return 0;
}
