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

enum {
    num_philosophers = 4,
    think_seconds = 3,
    eat_seconds = 1
};

enum possible_states {
    thinking,
    hungry,
    eating
};

typedef struct {
    sem_t data_sem;
    int state[num_philosophers];
    pthread_mutex_t state_mut;
    sem_t events[num_philosophers];
    int i;
} data_t;

static void data_init(data_t *d)
{
    int i;

    sem_init(&d->data_sem, 0, 0);
    pthread_mutex_init(&d->state_mut, NULL);
    for (i = 0; i < num_philosophers; i++) {
        d->state[i] = thinking;
        sem_init(&d->events[i], 0, 0);
    }
}

static void data_destroy(data_t *d)
{
    int i;

    sem_destroy(&d->data_sem);
    pthread_mutex_destroy(&d->state_mut);
    for (i = 0; i < num_philosophers; i++)
        sem_destroy(&d->events[i]);
}

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

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

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

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

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

static void *philosopher(void *data)
{
    data_t *d = data;
    int i = d->i;
    sem_post(&d->data_sem);

    while (1) {
        think(i);

        pthread_mutex_lock(&d->state_mut);
        d->state[i] = hungry;
        test(d, i);
        pthread_mutex_unlock(&d->state_mut);

        sem_wait(&d->events[i]);
        eat(i);

        pthread_mutex_lock(&d->state_mut);
        d->state[i] = thinking;
        test(d, left_of(i));
        test(d, right_of(i));
        pthread_mutex_unlock(&d->state_mut);

    }

    return NULL;
}

int main()
{
    int i, failed;
    pthread_t t[num_philosophers];
    data_t d;

    data_init(&d);

    for (i = 0; i < num_philosophers; i++) {
        d.i = i;

        failed = pthread_create(&t[i], NULL, philosopher, &d);
        if (failed) {
            fprintf(stderr, "pthread_create failed\n");
            return 1;
        }

        sem_wait(&d.data_sem);
    }

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

    data_destroy(&d);

    return 0;
}
