diff options
| author | yctct <yctct@yctct.com> | 2026-09-13 18:58:14 +0200 |
|---|---|---|
| committer | yctct <yctct@yctct.com> | 2026-09-13 18:58:14 +0200 |
| commit | 47beba686ff9d2aab63738fba7176a5235703d05 (patch) | |
| tree | f839ed36a9e9d4476fcdc59379b17903abfa35c8 /src/philos.c | |
Add all files, first commit
Diffstat (limited to 'src/philos.c')
| -rw-r--r-- | src/philos.c | 83 |
1 files changed, 83 insertions, 0 deletions
diff --git a/src/philos.c b/src/philos.c new file mode 100644 index 0000000..17cb34d --- /dev/null +++ b/src/philos.c @@ -0,0 +1,83 @@ +#include "codexion.h" +# include <stdlib.h> // for atoi(), malloc() + +t_philo *create_philo(t_sim *sim) +{ + t_philo *philo; + + philo = NULL; + philo = (t_philo *)malloc(sizeof(t_philo)); + if (!philo) + { + free_philos(sim); + free(sim); + return (NULL); + } + philo->beginning_last_eat_time = 0; + philo->number_of_eats_done = 0; + philo->ticket = 0; + philo->sim = sim; + return (philo); +} + +t_philo **create_arr_philos(t_sim *sim) +{ + t_philo **philos; + t_philo *philo; + int i; + int number_of_philos; + + number_of_philos = sim->number_of_philos; + philos = (t_philo **)malloc(sizeof(t_philo *) * (number_of_philos + 1)); + if (!philos) + { + free(sim); + return (NULL); + } + i = 0; + while (i < number_of_philos) + { + philo = create_philo(sim); + if (!philo) + return (NULL); + philo->id = i + 1; + philos[i++] = philo; + } + sim->number_of_philos_actual = i; + philos[i] = NULL; + sim->philos = philos; + return (philos); +} + +/* this function assigns 2 philos to each forks */ +/* the 'if' is used to assign the last philo to the */ +/* first fork. Then, in the 'else', the i is offset */ +/* by minus 1 to assign the first philo to the second */ +/* fork */ +t_fork **assign_philos(t_sim *sim) +{ + t_fork **forks; + t_philo **philos; + int number_of_philos; + int i; + + forks = sim->forks; + philos = sim->philos; + number_of_philos = sim->number_of_philos; + i = 0; + while (forks[i]) + { + if (i == 0) + { + forks[i]->left_philo = philos[number_of_philos - 1]; + forks[i]->right_philo = philos[i]; + } + else + { + forks[i]->left_philo = philos[i - 1]; + forks[i]->right_philo = philos[(i) % number_of_philos]; + } + i++; + } + return (forks); +} |
