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

volatile long long counter = 0;
long long niters;
sem_t mutex;

void *thread_func(void *arg)
{
    for (long long i = 0; i < niters; i++) {
        sem_wait(&mutex);
        counter++;
        sem_post(&mutex);
    }
    return NULL;
}

int main(int argc, char *argv[])
{
    if (argc != 2) {
        fprintf(stderr, "Usage: %s <niters>\n", argv[0]);
        return 1;
    }
    niters = atoll(argv[1]);

    sem_init(&mutex, 0, 1);

    pthread_t t1, t2;
    pthread_create(&t1, NULL, thread_func, NULL);
    pthread_create(&t2, NULL, thread_func, NULL);

    pthread_join(t1, NULL);
    pthread_join(t2, NULL);

    printf("Expected: %lld, Got: %lld\n", 2 * niters, counter);
    if (counter != 2 * niters) {
        printf("ERROR: Race condition detected!\n");
    } else {
        printf("Correct! No race condition.\n");
    }

    sem_destroy(&mutex);
    return 0;
}
