You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
85 lines
2.5 KiB
85 lines
2.5 KiB
/* ************************************************************************** */
|
|
/* */
|
|
/* ::: :::::::: */
|
|
/* philo_init.c :+: :+: :+: */
|
|
/* +:+ +:+ +:+ */
|
|
/* By: narnaud <narnaud@student.42.fr> +#+ +:+ +#+ */
|
|
/* +#+#+#+#+#+ +#+ */
|
|
/* Created: 2021/11/24 15:44:04 by narnaud #+# #+# */
|
|
/* Updated: 2022/05/20 08:38:02 by narnaud ### ########.fr */
|
|
/* */
|
|
/* ************************************************************************** */
|
|
|
|
#include "philo.h"
|
|
|
|
t_room *create_room(char **argv)
|
|
{
|
|
t_room *room;
|
|
|
|
room = malloc(sizeof(t_room));
|
|
room->param[PHILO_AMOUNT] = mini_atoi(argv[0]);
|
|
room->param[DIE_TIME] = mini_atoi(argv[1]);
|
|
room->param[EAT_DURATION] = mini_atoi(argv[2]);
|
|
room->param[SLEEP_DURATION] = mini_atoi(argv[3]);
|
|
if (argv[4])
|
|
room->param[MEALS_AMOUNT] = mini_atoi(argv[4]);
|
|
else
|
|
room->param[MEALS_AMOUNT] = 2147483647;
|
|
room->lock = malloc(sizeof(pthread_mutex_t));
|
|
room->forks = (pthread_mutex_t *)malloc(
|
|
(room->param[PHILO_AMOUNT]) * sizeof(pthread_mutex_t));
|
|
pthread_mutex_init(room->lock, NULL);
|
|
room->running = 1;
|
|
return (room);
|
|
}
|
|
|
|
t_philo *create_philos(t_room *room)
|
|
{
|
|
t_philo *ret;
|
|
static int i;
|
|
int amount;
|
|
|
|
amount = room->param[PHILO_AMOUNT];
|
|
ret = (t_philo *)malloc((amount + 1) * sizeof(t_philo));
|
|
while (i < amount)
|
|
{
|
|
ret[i].fork = &room->forks[i];
|
|
if (amount > 1)
|
|
ret[i].fork_r = &room->forks[(i + 1) % amount];
|
|
ret[i].lock = malloc(sizeof(pthread_mutex_t));
|
|
ret[i].thd = malloc(sizeof(pthread_t));
|
|
ret[i].room = room;
|
|
ret[i].eat_amount = 0;
|
|
ret[i].id = i;
|
|
pthread_mutex_init(ret[i].fork, NULL);
|
|
pthread_mutex_init(ret[i++].lock, NULL);
|
|
}
|
|
ret[i].id = -1;
|
|
return (ret);
|
|
}
|
|
|
|
void invit_philos(t_philo *philos)
|
|
{
|
|
static int i;
|
|
t_room *room;
|
|
t_philo *philo;
|
|
|
|
philo = philos;
|
|
room = philo->room;
|
|
while (i >= 0)
|
|
{
|
|
philo->eat_time = room_clock();
|
|
pthread_create(philo->thd, NULL, philos_life, (void *)philo);
|
|
pthread_detach(*philo->thd);
|
|
if ((i % 2) == 0)
|
|
{
|
|
i += 2;
|
|
if (i >= room->param[PHILO_AMOUNT])
|
|
i -= 1 + (room->param[PHILO_AMOUNT] % 2) * 2;
|
|
}
|
|
else if ((i % 2) == 1)
|
|
i -= 2;
|
|
philo = philos + i;
|
|
usleep(50);
|
|
}
|
|
}
|
|
|