#include "kernel/types.h"
#include "kernel/stat.h"
#include "user/user.h"

int lock = 0;

void worker(int *arg)
{
    int tid = *arg;
    free(arg);

    futex(&lock, FUTEX_LOCK, 1);
    printf("[thread-%d] woke up and acquired lock!\n", tid);
    
    // wake up any one thread based on priority
    futex(&lock, FUTEX_UNLOCK, 3);
    exit(0);
}

int main(int argc, char *argv[])
{
    if (argc != 2) {
        printf("Usage: %s <num_threads>\n", argv[0]);
        exit(1);
    }

    int nthreads = atoi(argv[1]);

    futex(&lock, FUTEX_LOCK, 1);
    printf("[pid %d main] launching %d threads\n", getpid(), nthreads);
    for (int i = 0; i < nthreads; i++) {
        printf("[pid %d main] launching thread-%d with priority %d\n", getpid(), i, i % 2);

        int *thread_id = malloc(sizeof(int));
        *thread_id = i;

        int thread_pid = create_thread(worker, thread_id);
        set_priority(thread_pid, i % 2);
    }
    // wait for all threads to start
    pause(5);

    // wake up one thread based on priority
    futex(&lock, FUTEX_UNLOCK, 3);

    for (int i = 0; i < nthreads; i++) {
        join();
    }

    printf("[pid %d main] all threads joined\n", getpid());

    exit(0);
}
