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.
83 lines
2.5 KiB
83 lines
2.5 KiB
3 years ago
|
/* ************************************************************************** */
|
||
|
/* */
|
||
|
/* ::: :::::::: */
|
||
|
/* philo_init.c :+: :+: :+: */
|
||
|
/* +:+ +:+ +:+ */
|
||
|
/* By: narnaud <narnaud@student.42.fr> +#+ +:+ +#+ */
|
||
|
/* +#+#+#+#+#+ +#+ */
|
||
|
/* Created: 2021/11/24 15:44:04 by narnaud #+# #+# */
|
||
|
/* Updated: 2022/05/19 00:47:38 by narnaud@stude ### ########.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;
|
||
|
|
||
|
ret = (t_philo *)malloc((room->param[PHILO_AMOUNT] + 1) * sizeof(t_philo));
|
||
|
while (i < room->param[PHILO_AMOUNT])
|
||
|
{
|
||
|
ret[i].fork = &room->forks[i];
|
||
|
ret[i].fork_r = &room->forks[(i + 1) % room->param[PHILO_AMOUNT]];
|
||
|
ret[i].lock = malloc(sizeof(pthread_mutex_t));
|
||
|
ret[i].thd = malloc(sizeof(pthread_t));
|
||
|
ret[i].room = room;
|
||
|
ret[i].eat_time = room_clock();
|
||
|
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)
|
||
|
{
|
||
|
pthread_create(philo->thd, NULL, philos_life, (void *)philo);
|
||
|
pthread_detach(*philo->thd);
|
||
|
usleep(100);
|
||
|
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;
|
||
|
}
|
||
|
}
|