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


unsigned int counter = 0;
pthread_spinlock_t lock;

#define NUM_THREADS 4 

void* counter_thread(void* arg) {

  for (int i = 0; i < 10000000; i++) {
    pthread_spin_lock(&lock);
    counter++;
	sleep(1);
    pthread_spin_unlock(&lock);
  }
  pthread_exit(NULL);
}

int main() {
  pthread_t threads[NUM_THREADS];

  if (pthread_spin_init(&lock, PTHREAD_PROCESS_PRIVATE) != 0) {
        perror("Init failed");
        return 1;
  }


  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;
}
