42 school project
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.

73 lines
1.8 KiB

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* philo_utils.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: narnaud@student.42nice.fr <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/05/18 19:10:41 by narnaud@stude #+# #+# */
/* Updated: 2022/05/18 19:27:30 by narnaud@stude ### ########.fr */
/* */
/* ************************************************************************** */
#include "philosophers.h"
int is_running(t_room *room)
{
int ret;
pthread_mutex_lock(room->lock);
ret = room->running;
pthread_mutex_unlock(room->lock);
return (ret);
}
int safe_print(char *str, t_room *room, int id)
{
int ret;
ret = is_running(room);
if (!ret)
return (0);
printf(str, room_clock(), id);
return (ret);
}
int safe_wait(t_room *room, int start, int duration)
{
int ret;
ret = is_running(room);
while (ret && (room_clock() < (start + duration)))
{
ret = is_running(room);
usleep(50);
}
return (ret);
}
int room_clock()
{
struct timeval time;
int ret;
static long int start_time = 0;
gettimeofday(&time, NULL);
if (!start_time)
start_time = time.tv_sec * 1000 + time.tv_usec / 1000;
ret = (int)(time.tv_sec * 1000 + time.tv_usec / 1000 - start_time);
return (ret);
}
int mini_atoi(char *nbr)
{
int ret;
ret = 0;
while (*nbr >= '0' && *nbr <= '9')
{
ret = (*nbr - '0') + (10 * ret);
nbr++;
}
return (ret);
}