#define _POSIX_C_SOURCE 200809L
#include <pthread.h>
#include <stdatomic.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

static pthread_mutex_t table_lock = PTHREAD_MUTEX_INITIALIZER;
static unsigned long table[64];
static atomic_int done;
static int fixed_mode;

static void sleep_ms(long ms) {
    struct timespec ts = { ms / 1000, (ms % 1000) * 1000000L };
    nanosleep(&ts, NULL);
}

static double now_ms(void) {
    struct timespec ts;
    clock_gettime(CLOCK_MONOTONIC, &ts);
    return ts.tv_sec * 1e3 + ts.tv_nsec / 1e6;
}

/* Background thread: copies the table and "writes it out" (simulated by a 30 ms sleep). */
__attribute__((noinline)) unsigned long flush_table(void) {
    unsigned long snapshot[64], total = 0;
    pthread_mutex_lock(&table_lock);
    memcpy(snapshot, table, sizeof snapshot);
    if (!fixed_mode)
        sleep_ms(30); /* BUG: the slow step runs while the lock is held */
    pthread_mutex_unlock(&table_lock);
    if (fixed_mode)
        sleep_ms(30); /* FIX: the slow step runs after the lock is released */
    for (int i = 0; i < 64; i++)
        total += snapshot[i];
    return total;
}

static void *flusher(void *arg) {
    (void)arg;
    while (!atomic_load(&done)) {
        flush_table();
        sleep_ms(1);
    }
    return NULL;
}

/* Roughly half a millisecond of arithmetic per job. */
__attribute__((noinline)) unsigned long compute_job(int id) {
    unsigned long h = (unsigned long)id;
    for (int i = 0; i < 400000; i++)
        h = h * 6364136223846793005UL + 1442695040888963407UL;
    return h >> 60;
}

__attribute__((noinline)) void record_job(int id, unsigned long value) {
    pthread_mutex_lock(&table_lock);
    table[id % 64] += value;
    pthread_mutex_unlock(&table_lock);
}

int main(int argc, char **argv) {
    int jobs = argc > 1 ? atoi(argv[1]) : 200;
    fixed_mode = argc > 2 && strcmp(argv[2], "fixed") == 0;
    unsigned long sum = 0;
    pthread_t thread;
    if (jobs <= 0 || pthread_create(&thread, NULL, flusher, NULL) != 0) {
        fprintf(stderr, "usage: %s [jobs>0] [slow|fixed]\n", argv[0]);
        return 2;
    }
    double start = now_ms();
    for (int i = 0; i < jobs; i++) {
        unsigned long value = compute_job(i);
        record_job(i, value);
        sum += value;
    }
    double elapsed = now_ms() - start;
    atomic_store(&done, 1);
    pthread_join(thread, NULL);
    printf("mode=%s jobs=%d sum=%lu elapsed=%.0fms\n", fixed_mode ? "fixed" : "slow", jobs, sum, elapsed);
    return 0;
}
