/* =============================================================================
 * 03_deadlock.c -- a deadlock, caught in the act, then fixed by ordering
 * =============================================================================
 *
 * [Idea]
 *   Two threads, two mutexes. Thread A locks them in the order (1, 2); thread B
 *   locks them in the order (2, 1). Sooner or later A holds 1 and wants 2 while
 *   B holds 2 and wants 1. Neither will release what it has, so neither
 *   proceeds, forever. That is DEADLOCK, and it needs four conditions at once:
 *
 *     1. mutual exclusion   -- the resources cannot be shared
 *     2. hold and wait      -- a thread holding one waits for another
 *     3. no pre-emption     -- nobody can take a lock away
 *     4. circular wait      -- A waits for B which waits for A
 *
 *   Break any one and deadlock is impossible. The practical fix is to break
 *   (4): define a global ORDER on the locks and make every thread acquire them
 *   in that order. If all threads take 1 before 2, no cycle can form.
 *
 * [How a demo can show a deadlock and still terminate]
 *   A deadlocked program hangs by definition, so the broken version runs in a
 *   CHILD PROCESS (Lecture 16). The parent waits briefly, finds the child still
 *   alive, and reports the deadlock -- then kills it with SIGKILL (Lecture 17).
 *   The fixed version runs normally and finishes.
 *
 * [What it answers]
 *   - What exactly does a deadlock look like?
 *   - Which of the four conditions is practical to break, and how?
 *   - Why is lock ORDERING, not cleverness, the standard answer?
 *
 * Build & run:    make run
 * -----------------------------------------------------------------------------
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <pthread.h>
#include <sys/wait.h>
#include <sys/time.h>

#define NITERS 200000L
#define WAIT_MS 800             /* how long we give the broken version */

static pthread_mutex_t m1 = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t m2 = PTHREAD_MUTEX_INITIALIZER;
static long shared1 = 0, shared2 = 0;

/* ---- the BROKEN pair: opposite lock orders ------------------------------ */
static void *bad_a(void *v)
{
    (void)v;
    for (long i = 0; i < NITERS; i++) {
        pthread_mutex_lock(&m1);        /* order: 1 then 2 */
        pthread_mutex_lock(&m2);
        shared1++; shared2++;
        pthread_mutex_unlock(&m2);
        pthread_mutex_unlock(&m1);
    }
    return NULL;
}

static void *bad_b(void *v)
{
    (void)v;
    for (long i = 0; i < NITERS; i++) {
        pthread_mutex_lock(&m2);        /* order: 2 then 1  <-- the bug */
        pthread_mutex_lock(&m1);
        shared1++; shared2++;
        pthread_mutex_unlock(&m1);
        pthread_mutex_unlock(&m2);
    }
    return NULL;
}

/* ---- the FIXED pair: both use the same order --------------------------- */
/* The rule: m1 is always acquired before m2. Any consistent global order
 * works; what matters is that EVERY thread obeys the same one. */
static void *good_a(void *v)
{
    (void)v;
    for (long i = 0; i < NITERS; i++) {
        pthread_mutex_lock(&m1);
        pthread_mutex_lock(&m2);
        shared1++; shared2++;
        pthread_mutex_unlock(&m2);
        pthread_mutex_unlock(&m1);
    }
    return NULL;
}

static void *good_b(void *v)
{
    (void)v;
    for (long i = 0; i < NITERS; i++) {
        pthread_mutex_lock(&m1);        /* same order as good_a */
        pthread_mutex_lock(&m2);
        shared1 += 2; shared2 += 2;
        pthread_mutex_unlock(&m2);
        pthread_mutex_unlock(&m1);
    }
    return NULL;
}

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

int main(void)
{
    /* ---- experiment 1: the broken version, in a disposable child ------- */
    printf("== 1. opposite lock orders: thread A takes (m1,m2), B takes (m2,m1) ==\n");
    fflush(stdout);                 /* flush BEFORE fork (Lecture 18) */

    pid_t pid = fork();
    if (pid < 0) { perror("fork"); return 1; }
    if (pid == 0) {
        /* The child may deadlock. If it does, it never returns. */
        pthread_t a, b;
        pthread_create(&a, NULL, bad_a, NULL);
        pthread_create(&b, NULL, bad_b, NULL);
        pthread_join(a, NULL);
        pthread_join(b, NULL);
        _exit(0);                   /* reached only if it got lucky */
    }

    /* Parent: poll for the child for a while. */
    int status = 0;
    double t0 = now_ms();
    pid_t w = 0;
    while (now_ms() - t0 < WAIT_MS) {
        w = waitpid(pid, &status, WNOHANG);
        if (w == pid) break;        /* the child finished on its own */
        usleep(10 * 1000);
    }

    if (w == pid) {
        printf("  the child finished in %.0f ms without deadlocking this time\n",
               now_ms() - t0);
        printf("  (that happens: the deadlock needs the two threads to\n");
        printf("   interleave just so. Run it again -- it is a LATENT bug,\n");
        printf("   which is exactly what makes deadlocks dangerous.)\n");
    } else {
        printf("  after %d ms the child is STILL RUNNING and has made no\n", WAIT_MS);
        printf("  progress: A holds m1 and wants m2, B holds m2 and wants m1.\n");
        printf("  DEADLOCK confirmed -- killing it with SIGKILL.\n");
        kill(pid, SIGKILL);         /* SIGKILL cannot be caught or ignored */
        waitpid(pid, &status, 0);
        printf("  child terminated by signal %d (%s)\n",
               WIFSIGNALED(status) ? WTERMSIG(status) : -1,
               WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL
                   ? "SIGKILL" : "other");
    }

    /* ---- experiment 2: the ordered version, in this process ------------ */
    printf("\n== 2. the fix: EVERY thread acquires m1 before m2 ==\n");
    shared1 = shared2 = 0;
    pthread_t a, b;
    t0 = now_ms();
    pthread_create(&a, NULL, good_a, NULL);
    pthread_create(&b, NULL, good_b, NULL);
    pthread_join(a, NULL);
    pthread_join(b, NULL);
    double ms = now_ms() - t0;

    long expected = NITERS * 3;     /* good_a adds 1, good_b adds 2, each NITERS */
    printf("  finished in %.0f ms (no deadlock possible)\n", ms);
    printf("  shared1 = %ld, shared2 = %ld, expected %ld -> %s\n",
           shared1, shared2, expected,
           (shared1 == expected && shared2 == expected) ? "CORRECT" : "WRONG");

    printf("\nObservations\n------------\n");
    printf("- The broken version has no bug in either thread taken alone. Each\n");
    printf("  locks both mutexes and unlocks both. The bug is in the RELATIONSHIP\n");
    printf("  between them: opposite orders permit a circular wait.\n");
    printf("- It is a LATENT bug. The deadlock needs a particular interleaving,\n");
    printf("  so the program can pass tests for a long time and then stop dead\n");
    printf("  in production. No amount of testing proves its absence.\n");
    printf("- The fix is not cleverness but a CONVENTION: pick a global order on\n");
    printf("  the locks (here m1 before m2) and have every thread obey it. That\n");
    printf("  breaks the circular-wait condition, so no cycle can form at all.\n");
    printf("- Other ways to break the four conditions: take all locks at once\n");
    printf("  with a single 'lock both' primitive (no hold-and-wait); use\n");
    printf("  trylock and back off, releasing what you hold (adds pre-emption,\n");
    printf("  and risks livelock); or avoid shared state so there is nothing to\n");
    printf("  lock (best of all -- Lecture 22's private accumulators).\n");
    return 0;
}
