diff options
| author | Charles <sircharlesaze@gmail.com> | 2020-02-09 03:33:24 +0100 |
|---|---|---|
| committer | Charles <sircharlesaze@gmail.com> | 2020-02-09 03:33:24 +0100 |
| commit | dfbafce6506fe5c47b0e60289a9d4629e502c9ac (patch) | |
| tree | bff26d329d67b4d5f4f74dff4099743836ac8efb /common/philo.c | |
| parent | 34058c2901f18fd11a6e50e9fa8e3faefdcc6c7b (diff) | |
| download | philosophers-dfbafce6506fe5c47b0e60289a9d4629e502c9ac.tar.gz philosophers-dfbafce6506fe5c47b0e60289a9d4629e502c9ac.tar.bz2 philosophers-dfbafce6506fe5c47b0e60289a9d4629e502c9ac.zip | |
Added common files
Diffstat (limited to 'common/philo.c')
| -rw-r--r-- | common/philo.c | 66 |
1 files changed, 66 insertions, 0 deletions
diff --git a/common/philo.c b/common/philo.c new file mode 100644 index 0000000..b8d7caf --- /dev/null +++ b/common/philo.c @@ -0,0 +1,66 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* philo.c :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: cacharle <marvin@42.fr> +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2020/02/09 01:54:53 by cacharle #+# #+# */ +/* Updated: 2020/02/09 03:26:07 by cacharle ### ########.fr */ +/* */ +/* ************************************************************************** */ + +#include "common.h" + +t_philo *philos_new(int num, t_philo_routine routine) +{ + int i; + t_philo *philos; + + if (num < 0) + return (NULL); + if ((philos = (t_philo*)h_calloc(num + 1, sizeof(t_philo))) == NULL) + return (NULL); + i = -1; + while (++i < num) + { + philos[i].id = num + 1; + if (pthread_create(&philos[i].thread, NULL, routine, philos + num) != 0) + { + philos_destroy(philos, i); + return (NULL); + } + } + return (philos); +} + +void philos_destroy(t_philo *philo, int num) +{ + if (philo == NULL) + return ; + while (num-- > 0) + pthread_join(philos[num].thread, NULL); + free(philos); +} + +void philo_eat(t_philo *philo) +{ + // take forks + // lock mutex + philo_put_state_change(philo, EVENT_EATING); + usleep(philo->timeout_eat * 1000); + // drop forks + // unlock mutex +} + +void philo_sleep(t_philo *philo) +{ + philo_put_state_change(philo, EVENT_SLEEPING); + usleep(philo->timeout_sleep * 1000); +} + +void philo_think(t_philo *philo) +{ + philo_put_state_change(philo, EVENT_THINKING); + // search a fork +} |
