42_Philosopher/data.c
Camille Chauvet 531d3146e4 merge
2023-04-25 11:30:55 +00:00

62 lines
1.3 KiB
C

#include <pthread.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdlib.h>
#include <unistd.h>
#include "./data.h"
#include "philo.h"
#include "philos.h"
#include "struct.h"
#include <string.h>
bool data_init(t_data *data)
{
data->stop = 0;
data->forks = malloc(sizeof(bool) * data->nb_philos);
if (data->forks == NULL)
return (1);
memset(data->forks, 1, data->nb_philos);
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);
}
pthread_mutex_init(&data->forks_mutex, NULL);
pthread_mutex_init(&data->stop_mutex, NULL);
pthread_mutex_init(&data->print_mutex, NULL);
return (0);
}
void data_destroyer(t_data *data)
{
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++;
usleep(1000);
}
pthread_mutex_destroy(&data->forks_mutex);
pthread_mutex_destroy(&data->stop_mutex);
pthread_mutex_destroy(&data->print_mutex);
free(data->threads);
free(data->forks);
philos_destroyer(data);
}