diff options
Diffstat (limited to 'src/scheduler.c')
| -rw-r--r-- | src/scheduler.c | 86 |
1 files changed, 86 insertions, 0 deletions
diff --git a/src/scheduler.c b/src/scheduler.c new file mode 100644 index 0000000..76c2f8d --- /dev/null +++ b/src/scheduler.c @@ -0,0 +1,86 @@ +#include "codexion.h" +# include <unistd.h> // for usleep() +# include <string.h> // for strcmp() + +static t_ticket take_ticket(t_philo *philo, t_fork *fork) +{ + t_ticket my_ticket; + char *scheduler; + t_sim *sim; + + (void)pthread_mutex_lock(&philo->sim->mutex_scheduler); + scheduler = philo->sim->scheduler; + (void)pthread_mutex_unlock(&philo->sim->mutex_scheduler); + if (strcmp(scheduler, "fifo") == 0) + { + (void)pthread_mutex_lock(&fork->mutex_ticket_next); + my_ticket.num = fork->ticket_next++; + (void)pthread_mutex_unlock(&fork->mutex_ticket_next); + } + if (strcmp(scheduler, "edf") == 0) + { + (void)pthread_mutex_lock(&philo->mutex_sim); + sim = philo->sim; + (void)pthread_mutex_unlock(&philo->mutex_sim); + my_ticket.num = get_rel_time(sim) + sim->time_to_starve; + } + enqueue(fork, my_ticket); + heapify(fork); + return (my_ticket); +} + +int get_first_item_queue(t_fork *fork) +{ + int first_item; + + (void)pthread_mutex_lock(&fork->mutex_pq); + first_item = fork->pq.items[0].num; + (void)pthread_mutex_unlock(&fork->mutex_pq); + return (first_item); +} + +static int is_ticket_first(t_philo *philo, t_fork *f1, + t_fork *f2, t_ticket ticket) +{ + t_sim *sim; + + (void)pthread_mutex_lock(&philo->mutex_sim); + sim = philo->sim; + (void)pthread_mutex_unlock(&philo->mutex_sim); + wait_for_longest_cooldown(philo, f1, f2); + (void)pthread_mutex_lock(&f1->mutex_cond); + while (ticket.num != get_first_item_queue(f1)) + { + if (check_if_philo_starved(sim)) + { + (void)pthread_mutex_unlock(&f1->mutex_cond); + return (1); + } + pthread_cond_wait(&f1->cond_signal, &f1->mutex_cond); + wait_for_longest_cooldown(philo, f1, f2); + } + (void)pthread_mutex_unlock(&f1->mutex_cond); + return (0); +} + +int queue_routine(t_philo *philo, t_fork *f1, t_fork *f2) +{ + t_ticket t1; + t_ticket t2; + //t_sim *sim; + + //(void)pthread_mutex_lock(&philo->mutex_sim); + //sim = philo->sim; + //(void)pthread_mutex_unlock(&philo->mutex_sim); + if (get_id(philo) % 2 != 0 && philo->number_of_eats_done < 1) + { + usleep(100); + } + t1 = take_ticket(philo, f1); + t2 = take_ticket(philo, f2); + if (is_ticket_first(philo, f1, f2, t1) == 1) + return (1); + if (is_ticket_first(philo, f2, f1, t2) == 1) + return (1); + return (0); +} |
