// gcc -std=c11 -pthread main.c
#include <stdio.h>
#include <stdatomic.h>
#include <threads.h>  // for thrd_t, thrd_create, etc.

// atomický čítač
atomic_int counter = 0;

// funkce pro vlákna
int incrementer(void *arg) {
    int id = *(int *)arg;
    for (int i = 0; i < 100000; ++i) {
        //fetch and add
        int old = atomic_fetch_add(&counter, 1);
        if (i % 50000 == 0)
            printf("Vlákno %d získaná hodnota: %d\n", id, old);
    }
    return 0;
}

int main(void) {

    //vlákna
    thrd_t t1, t2;
    int id1 = 1, id2 = 2;

    thrd_create(&t1, incrementer, &id1);
    thrd_create(&t2, incrementer, &id2);

    thrd_join(t1, NULL);
    thrd_join(t2, NULL);

    printf("Výsledý čítač: %d\n", atomic_load(&counter));

    // compare-and-swap 
    int expected = 200000;
    if (atomic_compare_exchange_strong(&counter, &expected, 0)) {
        printf("CAS resetuje čítač 0\n");
    } else {
        printf("CAS neočekávaná hodnota! chci %d,  mám %d\n", expected, atomic_load(&counter));
    }

    printf("Čítač: %d\n", counter);
    //exchabge/swap
    int old = atomic_exchange(&counter, 42);
    printf("Prohozena hodntoa %d s %d\n", old, atomic_load(&counter));
      printf("Čítač: %d\n", counter);

    return 0;
}
