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.

77 lines
1.9 KiB

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* philo_utils.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: narnaud@student.42nice.fr <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/05/18 19:10:41 by narnaud@stude #+# #+# */
3 years ago
/* Updated: 2022/05/19 00:50:56 by narnaud@stude ### ########.fr */
/* */
/* ************************************************************************** */
3 years ago
#include "philo.h"
int is_running(t_room *room)
{
int ret;
3 years ago
pthread_mutex_lock(room->lock);
ret = room->running;
pthread_mutex_unlock(room->lock);
return (ret);
}
3 years ago
int safe_print(t_philo *philo, char *str)
{
int ret;
3 years ago
ret = is_running(philo->room);
if (!ret)
return (0);
3 years ago
pthread_mutex_lock(philo->room->lock);
printf(str, room_clock(), philo->id);
pthread_mutex_unlock(philo->room->lock);
return (ret);
}
int safe_wait(t_room *room, int start, int duration)
{
int ret;
ret = is_running(room);
3 years ago
while (ret && (room_clock()
< (start + room->param[duration])))
{
ret = is_running(room);
usleep(50);
}
return (ret);
}
3 years ago
int room_clock(void)
{
struct timeval time;
3 years ago
int ret;
static long int start_time = 0;
gettimeofday(&time, NULL);
if (!start_time)
3 years ago
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++;
}
3 years ago
return (ret);
}