mutexes fial

This commit is contained in:
whaffman 2025-01-27 18:38:41 +01:00
parent dd686a4f85
commit a197fdc79c
5 changed files with 33 additions and 3 deletions

View File

@ -57,8 +57,10 @@ typedef struct s_philo
int death;
pthread_mutex_t *death_lock;
int last_meal;
pthread_mutex_t *last_meal_lock;
t_rules *rules;
int n_eat;
pthread_mutex_t *n_eat_lock;
} t_philo;
// memset, printf, malloc, free, write,

View File

@ -12,6 +12,22 @@
#include "philo.h"
int create_philo_mutexes(t_philo *philo)
{
philo->death_lock = malloc(sizeof(pthread_mutex_t));
philo->last_meal_lock = malloc(sizeof(pthread_mutex_t));
philo->n_eat_lock = malloc(sizeof(pthread_mutex_t));
if (!philo->death_lock || !philo->last_meal_lock || !philo->n_eat_lock)
return (FAILURE);
if (pthread_mutex_init(philo->death_lock, NULL))
return (FAILURE);
if (pthread_mutex_init(philo->last_meal_lock, NULL))
return (FAILURE);
if (pthread_mutex_init(philo->n_eat_lock, NULL))
return (FAILURE);
return (SUCCESS);
}
int create_mutexes(t_rules *rules)
{
int i;
@ -25,6 +41,8 @@ int create_mutexes(t_rules *rules)
{
if (pthread_mutex_init(&rules->forks[i], NULL))
return (FAILURE);
if (create_philo_mutexes(&rules->philos[i]) == FAILURE)
return (FAILURE);
i++;
}
return (SUCCESS);

View File

@ -24,7 +24,14 @@ int destroy_mutexes(t_rules *rules)
while (i < rules->n_philos)
{
if (pthread_mutex_destroy(&rules->forks[i]))
return (FAILURE);
return (printf("1"), FAILURE);
if (pthread_mutex_destroy(rules->philos[i].death_lock))
return (printf("2"), FAILURE);
// pthread_mutex_lock(rules->philos[i].last_meal_lock);
if (pthread_mutex_destroy(rules->philos[i].last_meal_lock))
return (printf("3: %d\n", i), perror("Error"), FAILURE);
if (pthread_mutex_destroy(rules->philos[i].n_eat_lock))
return (printf("4"), FAILURE);
i++;
}
return (SUCCESS);

View File

@ -19,6 +19,9 @@ void free_philos(t_rules *rules)
while (i < rules->n_philos)
{
free(rules->philos[i].pid);
free(rules->philos[i].death_lock);
free(rules->philos[i].last_meal_lock);
free(rules->philos[i].n_eat_lock);
i++;
}
free(rules->monitor);

View File

@ -18,10 +18,10 @@ int main(int argc, char *argv[])
if (FAILURE == parse_arguments(argc, argv, &rules))
return (printf(ERROR_USAGE), EXIT_FAILURE);
if (FAILURE == create_mutexes(&rules))
return (printf(ERROR_MUTEX), EXIT_FAILURE);
if (FAILURE == create_philos(&rules))
return (printf(ERROR_MALLOC), EXIT_FAILURE);
if (FAILURE == create_mutexes(&rules))
return (printf(ERROR_MUTEX), EXIT_FAILURE);
rules.start_time = get_time() + START_DELAY;
pthread_mutex_lock(rules.finished_lock);
if (FAILURE == create_threads(&rules))