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

int lock = 0;      // USE ONLY THIS LOCK
int nthreads = 0;

int *thread_order = 0;

void worker(int *arg)
{
    /* TODO: setup the worker thread */
    int tid = *arg;
    free(arg);
    printf("[pid %d thread-%d] acquired lock\n", getpid(), tid);
    exit(0);
}

int main(int argc, char *argv[])
{
    // DO NOT MODIFY THIS SECTION - START ///////////////////////////
    if (argc < 3) {
        printf("Usage: %s <nthreads> <thread_order[0]> ... <thread_order[nthreads-1]>\n",
               argv[0]);
        exit(1);
    }

    nthreads = atoi(argv[1]);

    if (nthreads <= 0) {
        printf("nthreads must be > 0\n");
        exit(1);
    }

    if (argc != nthreads + 2) {
        printf("Usage: %s <nthreads> <thread_order[0]> ... <thread_order[nthreads-1]>\n",
               argv[0]);
        exit(1);
    }

    thread_order = malloc(sizeof(int) * nthreads);

    for (int i = 0; i < nthreads; i++) {
        int tid = atoi(argv[i + 2]);
        thread_order[i] = tid;
    }

    // DO NOT MODIFY - END ///////////////////////////////////


    /* TODO: use the following print statements in your implementation */
    printf("[pid %d main] launching %d threads\n", getpid(), nthreads);
    printf("[pid %d main] thread order: ", getpid());
    for (int i = 0; i < nthreads; i++) {
        printf("%d", thread_order[i]);
        if (i != nthreads - 1)
            printf(" ");
    }
    printf("\n");

    pause(10); // wait for threads to start

    printf("[pid %d main] waking thread-%d first\n", getpid(), thread_order[0]);

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

    free(thread_order);
    exit(0);
}
