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

typedef struct {
    sem_t *sem_e; // Semáforo para el escritor
    sem_t *sem_l; // Semáforo para el lector
    int *val;
} argumentos;

void* escritor(void* arg) {
    argumentos *sol = (argumentos *)arg;
    for(int i=0; i<1; i++) { // Cada hilo hace su tarea
        sem_wait(sol->sem_e); // Espera turno para escribir
        (*(sol->val))++;
        sem_post(sol->sem_l); // Da turno al lector
    }
    return NULL;
}

void* lector(void* arg) {
    argumentos *sol = (argumentos *)arg;
    for(int i=0; i<1; i++) {
        sem_wait(sol->sem_l); // Espera a que el escritor termine
        printf("HE LEIDO %d \n", *(sol->val));
        sem_post(sol->sem_e); // Da turno al siguiente escritor
    }
    return NULL;
}

int main() {
    sem_t se, sl;
    sem_init(&se, 0, 1); // El escritor empieza habilitado (1)
    sem_init(&sl, 0, 0); // El lector empieza bloqueado (0)

    int *val = malloc(sizeof(int));
    *val = 4;
    pthread_t th_l[3], th_e[3];
    argumentos arg = {&se, &sl, val};

    for (int i = 0; i < 3; i++) {
        pthread_create(&th_e[i], NULL, escritor, &arg);
        pthread_create(&th_l[i], NULL, lector, &arg);
    }

    for (int i = 0; i < 3; i++) {
        pthread_join(th_e[i], NULL);
        pthread_join(th_l[i], NULL);
    }

    sem_destroy(&se);
    sem_destroy(&sl);
    free(val);
    return 0;
}