/* =============================================================================
 * 04_thread_safety.c -- why strtok is unsafe and strtok_r is fine
 * =============================================================================
 *
 * [Idea]
 *   A function is THREAD-SAFE if it always behaves correctly when called
 *   concurrently from several threads. CS:APP sorts unsafe functions into four
 *   classes:
 *
 *     Class 1  does not protect shared variables        -> add a lock
 *     Class 2  keeps state across calls (static state)  -> pass the state in
 *     Class 3  returns a pointer to a static buffer     -> lock-and-copy, or
 *                                                          use the _r variant
 *     Class 4  calls a class-1..3 function              -> inherit the problem
 *
 *   strtok() is the textbook Class 2 offender: it remembers where it stopped in
 *   a STATIC variable, so two threads tokenizing two different strings destroy
 *   each other's position. The fix is strtok_r(), where the caller supplies the
 *   state ("r" for reentrant), giving each thread its own.
 *
 *   This demo runs both versions from several threads on known inputs and
 *   COUNTS the wrong answers.
 *
 * [What it answers]
 *   - What does a Class 2 bug look like in practice?
 *   - How does passing the state in fix it?
 *   - Which familiar functions are in which class?
 *
 * Build & run:    make run
 *
 * The number of corrupted results varies run to run (it is a race); strtok is
 * essentially never fully correct here, and strtok_r is always correct.
 * -----------------------------------------------------------------------------
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <stdatomic.h>
#include <sched.h>

#define NTHREADS 8
#define NROUNDS  2000

/* Each thread tokenizes its OWN private string and knows how many tokens it
 * should get, so any other answer is a corruption caused by shared state. */
static const char *inputs[NTHREADS] = {
    "a b c",                                 /* 3 tokens */
    "one two three four",                    /* 4 */
    "x",                                     /* 1 */
    "alpha beta gamma delta epsilon",        /* 5 */
    "p q",                                   /* 2 */
    "l m n o p q",                           /* 6 */
    "single",                                /* 1 */
    "1 2 3 4 5 6 7",                         /* 7 */
};
static const int expected_tokens[NTHREADS] = { 3, 4, 1, 5, 2, 6, 1, 7 };

static atomic_long wrong_unsafe = 0, wrong_safe = 0;
static atomic_long calls_unsafe = 0, calls_safe = 0;

/* ---- the UNSAFE version: strtok keeps its position in static storage ----- */
static void *worker_unsafe(void *vargp)
{
    int id = *(int *)vargp;
    char buf[64];
    for (int r = 0; r < NROUNDS; r++) {
        /* strtok MODIFIES its input, so work on a private copy -- that part is
           fine. The problem is strtok's own hidden state, which is shared. */
        snprintf(buf, sizeof(buf), "%s", inputs[id]);
        int n = 0;
        for (char *t = strtok(buf, " "); t != NULL; t = strtok(NULL, " ")) {
            n++;
            /* [Idea] Yield between calls to WIDEN the race window. This does
               not create the bug -- it exposes one that is already there.
               Back-to-back strtok calls are so fast that the interleaving is
               rare (measured: ~1 failure in 16000 without this yield), which
               is precisely what makes the bug so dangerous in real code: it
               hides in testing and appears under load. The safe version below
               yields identically, so the comparison is fair. */
            sched_yield();
        }
        atomic_fetch_add(&calls_unsafe, 1);
        if (n != expected_tokens[id])
            atomic_fetch_add(&wrong_unsafe, 1);
    }
    return NULL;
}

/* ---- the SAFE version: strtok_r takes the state as an argument ---------- */
static void *worker_safe(void *vargp)
{
    int id = *(int *)vargp;
    char buf[64];
    for (int r = 0; r < NROUNDS; r++) {
        snprintf(buf, sizeof(buf), "%s", inputs[id]);
        char *saveptr = NULL;       /* OUR state, on OUR stack: private */
        int n = 0;
        for (char *t = strtok_r(buf, " ", &saveptr);
             t != NULL;
             t = strtok_r(NULL, " ", &saveptr)) {
            n++;
            sched_yield();          /* the same yield, for a fair comparison */
        }
        atomic_fetch_add(&calls_safe, 1);
        if (n != expected_tokens[id])
            atomic_fetch_add(&wrong_safe, 1);
    }
    return NULL;
}

static void run(void *(*fn)(void *))
{
    pthread_t tid[NTHREADS];
    int ids[NTHREADS];
    for (int i = 0; i < NTHREADS; i++) {
        ids[i] = i;
        pthread_create(&tid[i], NULL, fn, &ids[i]);
    }
    for (int i = 0; i < NTHREADS; i++)
        pthread_join(tid[i], NULL);
}

int main(void)
{
    printf("%d threads x %d rounds, each tokenizing its own private string\n\n",
           NTHREADS, NROUNDS);

    run(worker_unsafe);
    run(worker_safe);

    long cu = atomic_load(&calls_unsafe), wu = atomic_load(&wrong_unsafe);
    long cs = atomic_load(&calls_safe),   ws = atomic_load(&wrong_safe);

    printf("  %-28s %12s %12s %10s\n", "function", "calls", "wrong", "rate");
    printf("  %-28s %12s %12s %10s\n",
           "----------------------------", "------------", "------------",
           "----------");
    printf("  %-28s %12ld %12ld %9.2f%%\n",
           "strtok    (Class 2, unsafe)", cu, wu, 100.0 * (double)wu / (double)cu);
    printf("  %-28s %12ld %12ld %9.2f%%\n",
           "strtok_r  (reentrant, safe)", cs, ws, 100.0 * (double)ws / (double)cs);

    printf("\nObservations\n------------\n");
    printf("- strtok gave the WRONG token count %ld times out of %ld (%.1f%%),\n",
           wu, cu, 100.0 * (double)wu / (double)cu);
    printf("  even though every thread tokenized its own private buffer. The\n");
    printf("  shared thing was strtok's INTERNAL position pointer.\n");
    printf("- Both loops yield between calls to widen the window. Without that\n");
    printf("  yield the SAME broken code failed only about 1 time in 16000 --\n");
    printf("  it would pass almost any test suite, then fail in production.\n");
    printf("- strtok_r was wrong %ld times out of %ld. The only difference is\n",
           ws, cs);
    printf("  that the state lives in the caller's `saveptr` -- on each thread's\n");
    printf("  own stack -- instead of in one static variable.\n");
    printf("- This is CS:APP's Class 2: a function that keeps state across\n");
    printf("  calls. You cannot fix it with a lock around each call, because the\n");
    printf("  state must persist BETWEEN calls; the interface itself has to\n");
    printf("  change, which is why the _r variants exist.\n");
    printf("- Others to know: rand/srand (Class 2 -> rand_r), ctime/localtime\n");
    printf("  and asctime (Class 3, static buffer -> ctime_r/localtime_r),\n");
    printf("  gethostbyname (Class 3, obsolete -> getaddrinfo, L19). Anything\n");
    printf("  calling these inherits the problem (Class 4).\n");
    printf("- The general cure, in order of preference: share no state; pass the\n");
    printf("  state in (_r); lock and COPY the result before releasing the lock.\n");
    return 0;
}
