2021-05-15 22:06:30 +03:00

150 lines
2.4 KiB
C

#include "../includes/philo_header.h"
int check_f(char ch)
{
if (ch == '\t' || ch == '\n' || ch == ' ' || \
ch == '\v' || ch == '\f' || ch == '\r')
return (1);
else
return (0);
}
int ft_atoi(const char *str)
{
int i;
unsigned long int result;
int operator;
i = 0;
operator = 1;
result = 0;
while (check_f(str[i]))
i++;
if (str[i] == '-' || str[i] == '+')
{
if (str[i] == '-')
operator *= -1;
i++;
}
while (str[i] >= '0' && str[i] <= '9')
{
if (result > 922337203685477580 && operator == -1)
return (0);
else if (result > 922337203685477580 && operator == 1)
return (-1);
result = result * 10 + str[i] - '0';
i++;
}
return (result * operator);
}
void *ft_calloc(size_t num, size_t size)
{
void *addr;
unsigned int nbytes;
nbytes = num * size;
addr = malloc(nbytes);
if (!size || !num || (size == 0 && num == 0))
return ((void *)addr);
if (!addr)
return (NULL);
else
{
memset(addr, '\0', nbytes);
}
return ((void *)addr);
}
t_all *structalloc_and_bzero(void)
{
t_all *all;
all = ft_calloc(sizeof(t_all), 1);
all->number_of_philosophers = -1;
all->time_to_die = -1;
all->time_to_eat = -1;
all->time_to_sleep = -1;
all->number_of_times_each_philosopher_must_eat = -1;
return(all);
}
int return_big(int a, int b)
{
if (a > b)
{
return (a);
}
return (b);
}
int return_less(int a, int b)
{
if (a < b)
{
return (a);
}
return (b);
}
time_t ft_get_time(void)
{
time_t return_value;
struct timeval current_time;
gettimeofday(&current_time, NULL);
return_value = (current_time.tv_sec * 1000) + (current_time.tv_usec / 1000);
return (return_value);
}
void ft_msleep(time_t interval_ms)
{
time_t end_ms = ft_get_time() + interval_ms;
time_t now_ms = ft_get_time();
while (now_ms < end_ms)
{
usleep(_SLEEP_STEP);
now_ms = ft_get_time();
}
}
long get_time(void)
{
struct timeval time;
gettimeofday(&time, NULL);
return ((long)(time.tv_sec * 1000 + time.tv_usec / 1000));
}
void my_usleep(long time)
{
long t;
t = get_time();
while (get_time() - t < time)
usleep(1);
}
void ft_exit(t_all *all)
{
int i;
i = 0;
all->smert = 42;
ft_msleep(200);
while (i <= all->number_of_philosophers)
{
pthread_mutex_destroy(&all->data_philo->philors[i].eat_mutex);
pthread_mutex_destroy(&all->data_philo->mutex[i]);
i++;
}
i = 0;
while (i < all->number_of_philosophers)
{
free(&all->data_philo->philors[i]);
i++;
}
}