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.

91 lines
2.3 KiB

3 years ago
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* philo_utils.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: narnaud <narnaud@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/04/11 10:29:50 by narnaud #+# #+# */
3 years ago
/* Updated: 2022/05/16 18:03:12 by narnaud ### ########.fr */
3 years ago
/* */
/* ************************************************************************** */
#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);
}
3 years ago
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);
}
3 years ago
void safe_print(char *str, t_room *room, int id)
{
pthread_mutex_lock(room->safe);
3 years ago
printf(str, gettime(), id);
3 years ago
pthread_mutex_unlock(room->safe);
}
3 years ago
int safe_wait(t_room *room, size_t start, size_t duration)
3 years ago
{
int ret;
3 years ago
ret = 1;
while (ret && (gettime() < start + duration))
{
pthread_mutex_lock(room->safe);
if (!room->running)
ret = 0;
pthread_mutex_unlock(room->safe);
usleep(5000);
}
3 years ago
return (ret);
}
3 years ago
3 years ago
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);
}