|
|
|
/* ************************************************************************** */
|
|
|
|
/* */
|
|
|
|
/* ::: :::::::: */
|
|
|
|
/* philo_utils.c :+: :+: :+: */
|
|
|
|
/* +:+ +:+ +:+ */
|
|
|
|
/* By: narnaud <narnaud@student.42.fr> +#+ +:+ +#+ */
|
|
|
|
/* +#+#+#+#+#+ +#+ */
|
|
|
|
/* Created: 2022/04/11 10:29:50 by narnaud #+# #+# */
|
|
|
|
/* Updated: 2022/05/16 18:03:12 by narnaud ### ########.fr */
|
|
|
|
/* */
|
|
|
|
/* ************************************************************************** */
|
|
|
|
|
|
|
|
#include "philosophers.h"
|
|
|
|
|
|
|
|
|
|
|
|
int mini_atoi(char *nbr)
|
|
|
|
{
|
|
|
|
int ret;
|
|
|
|
|
|
|
|
ret = 0;
|
|
|
|
while (*nbr >= '0' && *nbr <= '9')
|
|
|
|
{
|
|
|
|
ret = (*nbr - '0') + (10 * ret);
|
|
|
|
nbr++;
|
|
|
|
}
|
|
|
|
return (ret);
|
|
|
|
}
|
|
|
|
|
|
|
|
size_t gettime(void)
|
|
|
|
{
|
|
|
|
static struct timeval start = {0,0};
|
|
|
|
struct timeval actualtime;
|
|
|
|
size_t ret;
|
|
|
|
|
|
|
|
if(start.tv_sec == 0 && start.tv_usec == 0)
|
|
|
|
gettimeofday(&start, NULL);
|
|
|
|
gettimeofday(&actualtime, NULL);
|
|
|
|
ret = (size_t)((actualtime.tv_sec * 1000 + actualtime.tv_usec / 1000)\
|
|
|
|
- (start.tv_sec * 1000 + start.tv_usec / 1000));
|
|
|
|
return (ret);
|
|
|
|
}
|
|
|
|
|
|
|
|
void safe_print(char *str, t_room *room, int id)
|
|
|
|
{
|
|
|
|
pthread_mutex_lock(room->safe);
|
|
|
|
printf(str, gettime(), id);
|
|
|
|
pthread_mutex_unlock(room->safe);
|
|
|
|
}
|
|
|
|
|
|
|
|
int safe_wait(t_room *room, size_t start, size_t duration)
|
|
|
|
{
|
|
|
|
int ret;
|
|
|
|
|
|
|
|
ret = 1;
|
|
|
|
while (ret && (gettime() < start + duration))
|
|
|
|
{
|
|
|
|
pthread_mutex_lock(room->safe);
|
|
|
|
if (!room->running)
|
|
|
|
ret = 0;
|
|
|
|
pthread_mutex_unlock(room->safe);
|
|
|
|
usleep(5000);
|
|
|
|
}
|
|
|
|
return (ret);
|
|
|
|
}
|
|
|
|
|
|
|
|
int clean_memory(t_room *room)
|
|
|
|
{
|
|
|
|
t_param *param;
|
|
|
|
int i;
|
|
|
|
|
|
|
|
i = 0;
|
|
|
|
param = room->param;
|
|
|
|
while (i < param->philo_amount)
|
|
|
|
{
|
|
|
|
pthread_mutex_destroy(room->philos[i]->safe);
|
|
|
|
pthread_mutex_destroy(room->philos[i]->fork);
|
|
|
|
free(room->philos[i]->safe);
|
|
|
|
free(room->philos[i]->fork);
|
|
|
|
free(room->philos[i]->thd);
|
|
|
|
free(room->philos[i]);
|
|
|
|
i++;
|
|
|
|
}
|
|
|
|
pthread_mutex_destroy(room->safe);
|
|
|
|
free(room->safe);
|
|
|
|
free(room->philos);
|
|
|
|
free(room->param);
|
|
|
|
free(room);
|
|
|
|
return (0);
|
|
|
|
}
|
|
|
|
|