#include <pthread.h>
#include <stdio.h>

#include <stdatomic.h>
#include <stdint.h>
#include <sys/syscall.h>
#include <linux/futex.h>
#include <unistd.h>

// 0: unlocked, 1: locked, 2: locked with waiters
typedef _Atomic uint32_t mutex_t;

static int futex_wait(mutex_t *addr, uint32_t val) {
    return syscall(SYS_futex, addr, FUTEX_WAIT, val, NULL, NULL, 0);
}

static int futex_wake(mutex_t *addr) {
    return syscall(SYS_futex, addr, FUTEX_WAKE, 1, NULL, NULL, 0);
}

void mutex_lock(mutex_t *m) {
    uint32_t c = 0;
    // Try to transition from 0 (unlocked) to 1 (locked)
    if (atomic_compare_exchange_strong(m, &c, 1))
        return; // Fast path: got the lock without contention

    // Slow path: mark as having waiters (2) and wait
    while (atomic_exchange(m, 2) != 0) {
        futex_wait(m, 2);
    }
}

void mutex_unlock(mutex_t *m) {
    // Set to 0 (unlocked). If previous state indicated waiters, wake one.
    if (atomic_fetch_sub(m, 1) != 1) {
        *m = 0;
        futex_wake(m);
    }
}



unsigned int counter = 0;
mutex_t lock;

#define NUM_THREADS 10 

void* counter_thread(void* arg) {

  for (int i = 0; i < 10000000; i++) {
    mutex_lock(&lock);
    counter++;
    mutex_unlock(&lock);
  }
}

int main() {
  pthread_t threads[NUM_THREADS];

  for (int i = 0; i < NUM_THREADS; i++) {
    if (pthread_create(&threads[i], NULL, counter_thread, NULL) != 0) {
      perror("Failed to create thread");
      return 1;
    }
  }

  for (int i = 0; i < NUM_THREADS; i++) {
    pthread_join(threads[i], NULL);
  }

  printf("Final counter value: %d\n", counter);

  return 0;
}
