#include "rwlock.h"

struct read_write_lock rwlock;
int shared_data = 0;

void* writer_func(void* arg) {
    int id = *(int*)arg;
    for (int i = 0; i < 1000; i++) {
        WriterLock(&rwlock);
        shared_data++;
        // printf("Writer %d wrote shared_data = %d\n", id, shared_data);
        usleep(100); //some busy loop to simulate work while holding the lock
        WriterUnlock(&rwlock);
        // usleep(50000);
    }
    return NULL;
}

int main() {
    // printf("Hi\n");
    InitalizeReadWriteLock(&rwlock);
    // printf("Hi\n");
    int num_writers = 500;
    pthread_t threads[num_writers];
    int ids[num_writers];

    for (int i = 0; i < num_writers; i++) {
        ids[i] = i + 1;
        pthread_create(&threads[i], NULL, writer_func, &ids[i]);
    }
    for (int i = 0; i < num_writers; i++) {
        pthread_join(threads[i], NULL);
    }

    printf("\nFinal shared_data = %d (expected %d)\n", shared_data, num_writers * 1000);
    return 0;
}
