// False sharing: iki thread FƏRQLİ sayğacları atomic artırır.
// Sayğaclar eyni cache line-dadırsa, core-lar line-ı bir-birinin əlindən alır.
// İstifadə: ./false_sharing D   D = iki sayğac arasındakı məsafə (byte)
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <stdatomic.h>
#include <time.h>

#define ITERS 100000000L

static char buf[4096] __attribute__((aligned(128)));   // 128 byte sərhədindən başlayır
static _Atomic long *counter[2];

static void *work(void *arg) {
    _Atomic long *c = counter[(long)arg];
    for (long i = 0; i < ITERS; i++)
        atomic_fetch_add_explicit(c, 1, memory_order_relaxed);   // x86-64: lock add
    return NULL;
}

int main(int argc, char **argv) {
    int d = argc > 1 ? atoi(argv[1]) : 8;
    counter[0] = (_Atomic long *)buf;
    counter[1] = (_Atomic long *)(buf + d);
    struct timespec t0, t1;
    clock_gettime(CLOCK_MONOTONIC, &t0);
    pthread_t a, b;
    pthread_create(&a, NULL, work, (void *)0);
    pthread_create(&b, NULL, work, (void *)1);
    pthread_join(a, NULL);
    pthread_join(b, NULL);
    clock_gettime(CLOCK_MONOTONIC, &t1);
    double ms = (t1.tv_sec - t0.tv_sec) * 1e3 + (t1.tv_nsec - t0.tv_nsec) / 1e6;
    printf("mesafe %3d byte: %6.0f ms\n", d, ms);
    return 0;
}
