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

enum {
    num_philosophers = 5
};

enum possible_states {
    hungry,
    eating,
    thinking
};

typedef struct {
    int state[num_philosophers];
    sem_t can_eat[num_philosophers];
    pthread_mutex_t state_mut;
} data_t;

typedef struct {
    data_t *data;
    int i;
} philosopher_data_t;

static int left(int i)
{
    return (i - 1 + num_philosophers) % num_philosophers;
}

int right(int i)
{
    return (i + 1) % num_philosophers;
}

static void think(int i)
{
    printf("Philosopher %d is thinking\n", i);
}

static void eat(int i)
{
    printf("Philosopher %d is eating\n", i);
}

static void test(data_t *d, int i)
{
    if (d->state[i] == hungry &&
            d->state[left(i)] != eating &&
            d->state[right(i)] != eating) {
        d->state[i] = eating;
        sem_post(&d->can_eat[i]);
    }
}

static void put_forks(data_t *d, int i)
{
    pthread_mutex_lock(&d->state_mut);
    d->state[i] = thinking;
    test(d, left(i));
    test(d, right(i));
    pthread_mutex_unlock(&d->state_mut);
}

static void take_forks(data_t *d, int i)
{
    pthread_mutex_lock(&d->state_mut);
    d->state[i] = hungry;
    test(d, i);
    pthread_mutex_unlock(&d->state_mut);
    sem_wait(&d->can_eat[i]);
}

static void *philosopher(void *data)
{
    philosopher_data_t *p = data;
    data_t *d = p->data;
    int i = p->i;

    while (1) {
        think(i);
        sleep(2);
        take_forks(d, i);
        eat(i);
        put_forks(d, i);
    }

    return NULL;
}

int main(int argc, char **argv)
{
    int i;
    pthread_t t[num_philosophers];
    philosopher_data_t p[num_philosophers];
    data_t d;

    for (i = 0; i < num_philosophers; i++) {
        d.state[i] = thinking;
        sem_init(&d.can_eat[i], 0, 0);
    }
    pthread_mutex_init(&d.state_mut, NULL);

    for (i = 0; i < num_philosophers; i++) {
        p[i].i = i;
        p[i].data = &d;
        pthread_create(&t[i], NULL, philosopher, &p[i]);
    }

    for (i = 0; i < num_philosophers; i++)
        pthread_join(t[i], NULL);

    for (i = 0; i < num_philosophers; i++)
        sem_destroy(&d.can_eat[i]);
    pthread_mutex_destroy(&d.state_mut);

    return 0;
}
