2023-04-13 09:00:39 -04:00
|
|
|
#include <pthread.h>
|
|
|
|
#include <stdbool.h>
|
|
|
|
#include <stddef.h>
|
|
|
|
#include <stdlib.h>
|
2023-04-19 10:01:59 -04:00
|
|
|
#include <unistd.h>
|
2023-04-13 09:00:39 -04:00
|
|
|
#include "./data.h"
|
|
|
|
#include "philo.h"
|
|
|
|
#include "philos.h"
|
2023-04-19 07:53:50 -04:00
|
|
|
#include <string.h>
|
2023-04-13 09:00:39 -04:00
|
|
|
|
|
|
|
bool data_init(t_data *data)
|
|
|
|
{
|
2023-04-25 10:32:42 -04:00
|
|
|
size_t i;
|
|
|
|
|
2023-04-25 07:30:55 -04:00
|
|
|
data->stop = 0;
|
2023-04-25 10:32:42 -04:00
|
|
|
data->forks = malloc(sizeof(pthread_mutex_t) * data->nb_philos);
|
2023-04-13 09:00:39 -04:00
|
|
|
if (data->forks == NULL)
|
|
|
|
return (1);
|
2023-04-19 07:53:50 -04:00
|
|
|
memset(data->forks, 1, data->nb_philos);
|
2023-04-13 09:00:39 -04:00
|
|
|
data->philos = malloc(sizeof(t_philo) * data->nb_philos);
|
|
|
|
if (data->philos == NULL)
|
|
|
|
{
|
|
|
|
free(data->forks);
|
|
|
|
return (1);
|
|
|
|
}
|
|
|
|
data->threads = malloc(sizeof(pthread_t) * data->nb_philos);
|
|
|
|
if (data->forks == NULL)
|
|
|
|
{
|
|
|
|
free(data->philos);
|
|
|
|
free(data->forks);
|
|
|
|
return (1);
|
|
|
|
}
|
2023-04-25 10:32:42 -04:00
|
|
|
i = 0;
|
|
|
|
while (i < data->nb_philos)
|
|
|
|
{
|
|
|
|
pthread_mutex_init(&data->forks[i], NULL);
|
|
|
|
i++;
|
|
|
|
}
|
2023-04-19 07:53:50 -04:00
|
|
|
pthread_mutex_init(&data->stop_mutex, NULL);
|
2023-04-20 08:40:30 -04:00
|
|
|
pthread_mutex_init(&data->print_mutex, NULL);
|
2023-04-13 09:00:39 -04:00
|
|
|
return (0);
|
|
|
|
}
|
|
|
|
|
|
|
|
void data_destroyer(t_data *data)
|
|
|
|
{
|
2023-04-19 10:01:59 -04:00
|
|
|
size_t i;
|
|
|
|
t_philo *philo;
|
|
|
|
bool stop;
|
|
|
|
|
|
|
|
i = 0;
|
|
|
|
while (i < data->nb_philos)
|
|
|
|
{
|
|
|
|
philo = data->philos[i];
|
|
|
|
pthread_mutex_lock(&philo->stop_mutex);
|
|
|
|
stop = philo->stop;
|
|
|
|
pthread_mutex_unlock(&philo->stop_mutex);
|
|
|
|
if (stop)
|
|
|
|
i++;
|
2023-04-19 10:49:48 -04:00
|
|
|
usleep(1000);
|
2023-04-19 10:01:59 -04:00
|
|
|
}
|
2023-04-25 10:32:42 -04:00
|
|
|
i = 0;
|
|
|
|
while (i < data->nb_philos)
|
|
|
|
{
|
|
|
|
pthread_mutex_destroy(&data->forks[i]);
|
|
|
|
i++;
|
|
|
|
}
|
2023-04-13 09:00:39 -04:00
|
|
|
pthread_mutex_destroy(&data->stop_mutex);
|
2023-04-20 08:40:30 -04:00
|
|
|
pthread_mutex_destroy(&data->print_mutex);
|
2023-04-19 10:01:59 -04:00
|
|
|
free(data->threads);
|
|
|
|
free(data->forks);
|
2023-04-13 09:00:39 -04:00
|
|
|
philos_destroyer(data);
|
|
|
|
}
|