/* =============================================================================
 * 01_producer_consumer.c -- a bounded buffer, with semaphores doing the counting
 * =============================================================================
 *
 * [Idea]
 *   Producers make items, consumers use them, and a fixed-size buffer sits
 *   between them. Three things must be true at once:
 *     1. MUTUAL EXCLUSION: only one thread touches the buffer's internals at a
 *        time (otherwise two producers write the same slot).
 *     2. A consumer must WAIT when the buffer is EMPTY.
 *     3. A producer must WAIT when the buffer is FULL.
 *
 *   A mutex alone gives (1) and nothing else -- it has no notion of "how many".
 *   This is where COUNTING semaphores earn their keep: use two of them as
 *   counters of availability.
 *
 *       items  -- initialized to 0: "how many items are in the buffer"
 *       slots  -- initialized to N: "how many empty slots are in the buffer"
 *
 *   Producer: P(slots) -> P(mutex) -> insert -> V(mutex) -> V(items)
 *   Consumer: P(items) -> P(mutex) -> remove -> V(mutex) -> V(slots)
 *
 *   Each side waits on the resource it CONSUMES and signals the one it
 *   PRODUCES. A producer consumes an empty slot and produces an item; a
 *   consumer does the reverse. That symmetry is the whole solution.
 *
 * [What it answers]
 *   - Why is a mutex not enough for a bounded buffer?
 *   - Why TWO semaphores, and which is initialized to what?
 *   - Why must P(slots) come BEFORE P(mutex)? (it is a deadlock otherwise)
 *
 * Build & run:    make run
 *
 * Verification: the consumers' checksum must equal the producers', and the
 * buffer's occupancy must never leave [0, N]. Both are checked, not assumed.
 * -----------------------------------------------------------------------------
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <sys/time.h>
#include "psem.h"

#define CAPACITY     8          /* slots in the buffer */
#define NPRODUCERS   3
#define NCONSUMERS   3
#define PER_PRODUCER 20000L     /* items each producer makes */
#define TOTAL_ITEMS  (NPRODUCERS * PER_PRODUCER)

/* ---- the bounded buffer -------------------------------------------------- */
typedef struct {
    long   slot[CAPACITY];
    int    front;               /* next position to remove from */
    int    rear;                /* next position to insert at   */
    int    count;               /* occupancy -- for checking only */
    int    max_count;           /* the highest occupancy ever seen */
    psem_t mutex;               /* (1) protects the fields above  */
    psem_t items;               /* (2) counts FULL slots          */
    psem_t slots;               /* (3) counts EMPTY slots         */
} sbuf_t;

static sbuf_t buf;

/* Totals, so we can prove nothing was lost or duplicated. */
static long produced_sum = 0, consumed_sum = 0;
static pthread_mutex_t sum_mutex = PTHREAD_MUTEX_INITIALIZER;

static void sbuf_init(sbuf_t *b)
{
    b->front = b->rear = b->count = b->max_count = 0;
    psem_init(&b->mutex, 1);            /* a binary semaphore: a lock       */
    psem_init(&b->items, 0);            /* no items yet                     */
    psem_init(&b->slots, CAPACITY);     /* every slot is empty              */
}

static void sbuf_destroy(sbuf_t *b)
{
    psem_destroy(&b->mutex);
    psem_destroy(&b->items);
    psem_destroy(&b->slots);
}

/* Insert one item, blocking while the buffer is full. */
static void sbuf_insert(sbuf_t *b, long item)
{
    psem_P(&b->slots);          /* wait for an empty slot  -- BEFORE the mutex */
    psem_P(&b->mutex);          /* now take the lock */

    b->slot[b->rear] = item;
    b->rear = (b->rear + 1) % CAPACITY;
    b->count++;
    if (b->count > b->max_count) b->max_count = b->count;

    psem_V(&b->mutex);          /* release the lock */
    psem_V(&b->items);          /* announce one more item */
}

/* Remove one item, blocking while the buffer is empty. */
static long sbuf_remove(sbuf_t *b)
{
    psem_P(&b->items);          /* wait for an item -- BEFORE the mutex */
    psem_P(&b->mutex);

    long item = b->slot[b->front];
    b->front = (b->front + 1) % CAPACITY;
    b->count--;

    psem_V(&b->mutex);
    psem_V(&b->slots);          /* announce one more empty slot */
    return item;
}

/* ---- the threads -------------------------------------------------------- */
static void *producer(void *vargp)
{
    long id = *(long *)vargp;
    long local = 0;
    for (long i = 0; i < PER_PRODUCER; i++) {
        long item = id * PER_PRODUCER + i;   /* a unique value per item */
        sbuf_insert(&buf, item);
        local += item;
    }
    pthread_mutex_lock(&sum_mutex);
    produced_sum += local;
    pthread_mutex_unlock(&sum_mutex);
    return NULL;
}

static void *consumer(void *vargp)
{
    long n = *(long *)vargp;        /* how many items this consumer takes */
    long local = 0;
    for (long i = 0; i < n; i++)
        local += sbuf_remove(&buf);
    pthread_mutex_lock(&sum_mutex);
    consumed_sum += local;
    pthread_mutex_unlock(&sum_mutex);
    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)
{
    pthread_t ptid[NPRODUCERS], ctid[NCONSUMERS];
    long pid_arg[NPRODUCERS], cid_arg[NCONSUMERS];

    sbuf_init(&buf);

    printf("bounded buffer: capacity %d, %d producers x %ld items, %d consumers\n",
           CAPACITY, NPRODUCERS, PER_PRODUCER, NCONSUMERS);
    printf("semaphore backend: %s\n\n", psem_backend());

    /* Split the work so consumers collectively take exactly TOTAL_ITEMS.
       (If they asked for more, the last ones would block forever on P(items)
       -- a termination problem every real pipeline must solve somehow.) */
    long per_consumer = TOTAL_ITEMS / NCONSUMERS;
    long remainder    = TOTAL_ITEMS % NCONSUMERS;

    double t0 = now_ms();
    for (int i = 0; i < NPRODUCERS; i++) {
        pid_arg[i] = i;
        pthread_create(&ptid[i], NULL, producer, &pid_arg[i]);
    }
    for (int i = 0; i < NCONSUMERS; i++) {
        cid_arg[i] = per_consumer + (i == 0 ? remainder : 0);
        pthread_create(&ctid[i], NULL, consumer, &cid_arg[i]);
    }
    for (int i = 0; i < NPRODUCERS; i++) pthread_join(ptid[i], NULL);
    for (int i = 0; i < NCONSUMERS; i++) pthread_join(ctid[i], NULL);
    double ms = now_ms() - t0;

    /* ---- verification ---------------------------------------------------- */
    long expected = 0;
    for (int id = 0; id < NPRODUCERS; id++)
        for (long i = 0; i < PER_PRODUCER; i++)
            expected += id * PER_PRODUCER + i;

    printf("  items produced/consumed : %ld / %ld\n", TOTAL_ITEMS, TOTAL_ITEMS);
    printf("  checksum produced       : %ld\n", produced_sum);
    printf("  checksum consumed       : %ld  -> %s\n", consumed_sum,
           consumed_sum == produced_sum ? "MATCH (nothing lost or duplicated)"
                                        : "MISMATCH");
    printf("  expected checksum       : %ld  -> %s\n", expected,
           expected == consumed_sum ? "correct" : "WRONG");
    printf("  buffer occupancy stayed : 0 .. %d (capacity %d) -> %s\n",
           buf.max_count, CAPACITY,
           buf.max_count <= CAPACITY ? "never overflowed" : "OVERFLOWED");
    printf("  final occupancy         : %d (should be 0)\n", buf.count);
    printf("  elapsed                 : %.0f ms\n", ms);

    printf("\nObservations\n------------\n");
    printf("- Every item crossed the buffer exactly once: the two checksums\n");
    printf("  match and equal the expected total. No item was lost (consumer\n");
    printf("  reading an empty slot) or duplicated (two consumers taking one).\n");
    printf("- Occupancy never exceeded %d with a capacity of %d: P(slots)\n",
           buf.max_count, CAPACITY);
    printf("  blocked the producers whenever the buffer filled, which a mutex\n");
    printf("  alone could never do -- a mutex cannot count.\n");
    printf("- The ORDER of the P operations matters. P(slots) comes BEFORE\n");
    printf("  P(mutex). Reverse them and a producer could hold the mutex while\n");
    printf("  waiting for a slot, so no consumer could ever get in to free one:\n");
    printf("  instant deadlock. Never block on a second resource while holding\n");
    printf("  a lock (demo 03 explores the general rule).\n");
    printf("- Each side waits on what it CONSUMES and signals what it PRODUCES.\n");
    printf("  That symmetry is why two semaphores suffice.\n");

    sbuf_destroy(&buf);
    return (consumed_sum == produced_sum && buf.count == 0) ? 0 : 1;
}
