/* =============================================================================
 * 03_thread_server.c -- a concurrent server: one THREAD per client
 * =============================================================================
 *
 * [Idea]
 *   A thread is a flow of control INSIDE a process. Threads of one process
 *   share the address space -- the same globals, the same heap, the same
 *   descriptors -- while each has its own stack, registers and program counter.
 *   So "one thread per client" gives the straight-line logic of the process-
 *   based server at a fraction of the cost: no new address space, no page-table
 *   copying, and switching between threads is cheaper than between processes.
 *
 *   Three idioms appear here and are each a classic trap:
 *     1. DETACH the thread (or join it). A thread that is neither joined nor
 *        detached leaks its resources when it finishes -- the thread version of
 *        Lecture 16's zombie.
 *     2. Do not pass a pointer to a variable the main thread keeps changing.
 *        Each thread gets its OWN malloc'd argument here; demo 04 shows what
 *        happens when you ignore this.
 *     3. The thread, not main, closes the connected descriptor -- because the
 *        descriptor is SHARED, closing it in main would break the thread.
 *
 * [What it answers]
 *   - What does a thread share with its peers, and what is private?
 *   - Why detach, and why malloc the argument?
 *   - Why is thread-based the usual choice, and what does it risk?
 *
 * Usage:   ./03_thread_server [port] [max_connections]
 *          defaults: 15223, 8
 * -----------------------------------------------------------------------------
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <pthread.h>
#include <sys/socket.h>
#include "netutil.h"
#include "rio.h"

#define MAXLINE 8192

/* Shared by every thread (they are in one address space). Incrementing this
 * from several threads is a RACE -- the subject of Lecture 22. Here each
 * thread touches it once under a mutex, which is the correct fix. */
static int served = 0;
static pthread_mutex_t served_mutex = PTHREAD_MUTEX_INITIALIZER;

/* The per-client thread routine. Its single void* argument is the convention
 * pthread_create forces: one pointer in, one pointer out. */
static void *serve_client(void *vargp)
{
    /* (2) The argument is a pointer to memory malloc'd FOR US by the acceptor.
           Copy the value out and free it immediately, so nothing else can
           change it and nothing leaks. */
    int connfd = *((int *)vargp);
    free(vargp);

    /* (1) Detach ourselves: nobody will pthread_join us, so ask the system to
           release our resources automatically when we return. */
    pthread_detach(pthread_self());

    rio_t rio;
    char  buf[MAXLINE];
    rio_readinitb(&rio, connfd);        /* a stack-local rio_t: PRIVATE to us */

    int lines = 0;
    ssize_t n;
    while ((n = rio_readlineb(&rio, buf, MAXLINE)) > 0) {
        rio_writen(connfd, buf, (size_t)n);
        lines++;
    }

    /* (3) We own this descriptor; close it here, not in main. */
    close(connfd);

    pthread_mutex_lock(&served_mutex);
    served++;                           /* shared counter, protected */
    pthread_mutex_unlock(&served_mutex);

    printf("[thread-server] thread for fd %d echoed %d line(s), done\n",
           connfd, lines);
    fflush(stdout);
    return NULL;
}

int main(int argc, char **argv)
{
    const char *port = (argc > 1) ? argv[1] : "15223";
    int maxconn      = (argc > 2) ? atoi(argv[2]) : 8;

    int listenfd = open_listenfd(port);
    if (listenfd < 0) { fprintf(stderr, "cannot listen on %s\n", port); return 1; }
    printf("[thread-server] listening on 127.0.0.1:%s, one thread per client, "
           "up to %d\n", port, maxconn);
    fflush(stdout);

    for (int i = 0; i < maxconn; i++) {
        int connfd = accept(listenfd, NULL, NULL);
        if (connfd < 0) {
            if (errno == EINTR) continue;
            perror("accept");
            break;
        }

        /* Give the new thread its OWN copy of the descriptor number. Passing
           &connfd would hand every thread the SAME address, which the next
           accept() overwrites -- demo 04 is that bug, measured. */
        int *argp = malloc(sizeof(int));
        if (!argp) { perror("malloc"); close(connfd); continue; }
        *argp = connfd;

        pthread_t tid;
        int rc = pthread_create(&tid, NULL, serve_client, argp);
        if (rc != 0) {
            fprintf(stderr, "pthread_create: %s\n", strerror(rc));
            free(argp);
            close(connfd);
            continue;
        }
        /* Note: main does NOT close connfd -- the thread shares and owns it. */
    }

    /* Wait for the last threads to finish (they are detached, so poll the
       protected counter rather than joining). */
    for (int waited = 0; waited < 300; waited++) {
        pthread_mutex_lock(&served_mutex);
        int done = served;
        pthread_mutex_unlock(&served_mutex);
        if (done >= maxconn) break;
        usleep(10 * 1000);
    }

    close(listenfd);
    printf("[thread-server] done; %d client(s) served\n", served);

    printf("\nObservations\n------------\n");
    printf("- Each client got a thread with its own STACK (its own rio_t, buf,\n");
    printf("  loop counter), while globals, the heap and DESCRIPTORS were shared.\n");
    printf("  That split is the whole thread model.\n");
    printf("- Threads are cheaper than processes (no address space to copy) and\n");
    printf("  switching between them is cheaper -- the usual reason to pick them.\n");
    printf("- The price is sharing: the `served` counter needed a mutex, because\n");
    printf("  two threads doing served++ can lose an update (Lecture 22).\n");
    printf("- Each thread was DETACHED and got its own malloc'd argument. Skip\n");
    printf("  the first and resources leak; skip the second and you get demo\n");
    printf("  04's bug, where threads serve the wrong descriptor.\n");
    return 0;
}
