bozosujet
This commit is contained in:
79
philo/data.c
Normal file
79
philo/data.c
Normal file
@ -0,0 +1,79 @@
|
||||
/* ************************************************************************** */
|
||||
/* */
|
||||
/* ::: :::::::: */
|
||||
/* data.c :+: :+: :+: */
|
||||
/* +:+ +:+ +:+ */
|
||||
/* By: cchauvet <cchauvet@student.42angouleme.fr +#+ +:+ +#+ */
|
||||
/* +#+#+#+#+#+ +#+ */
|
||||
/* Created: 2023/04/27 11:28:36 by cchauvet #+# #+# */
|
||||
/* Updated: 2023/05/05 16:58:45 by cchauvet ### ########.fr */
|
||||
/* */
|
||||
/* ************************************************************************** */
|
||||
|
||||
#include <pthread.h>
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/types.h>
|
||||
#include <unistd.h>
|
||||
#include "./data.h"
|
||||
#include "philo.h"
|
||||
#include "philos.h"
|
||||
#include <string.h>
|
||||
|
||||
bool data_init(t_data *data)
|
||||
{
|
||||
ssize_t i;
|
||||
|
||||
data->stop = 0;
|
||||
data->forks = malloc(sizeof(pthread_mutex_t) * 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);
|
||||
if (data->philos == NULL)
|
||||
return (1);
|
||||
data->threads = malloc(sizeof(pthread_t) * data->nb_philos);
|
||||
if (data->forks == NULL)
|
||||
{
|
||||
free(data->philos);
|
||||
free(data->forks);
|
||||
return (1);
|
||||
}
|
||||
i = -1;
|
||||
while (++i < (ssize_t) data->nb_philos)
|
||||
pthread_mutex_init(&data->forks[i], NULL);
|
||||
pthread_mutex_init(&data->stop_mutex, NULL);
|
||||
pthread_mutex_init(&data->print_mutex, NULL);
|
||||
return (0);
|
||||
}
|
||||
|
||||
void data_destroyer(t_data *data)
|
||||
{
|
||||
ssize_t i;
|
||||
t_philo *philo;
|
||||
bool stop;
|
||||
|
||||
i = 0;
|
||||
while (i < (ssize_t) 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);
|
||||
}
|
||||
usleep(1000);
|
||||
i = -1;
|
||||
while (++i < (ssize_t) data->nb_philos)
|
||||
pthread_mutex_destroy(&data->forks[i]);
|
||||
pthread_mutex_destroy(&data->stop_mutex);
|
||||
pthread_mutex_destroy(&data->print_mutex);
|
||||
free(data->threads);
|
||||
free(data->forks);
|
||||
philos_destroyer(data);
|
||||
}
|
||||
Reference in New Issue
Block a user