/ philo / cleanup.c
cleanup.c
 1  /* ************************************************************************** */
 2  /*                                                                            */
 3  /*                                                        :::      ::::::::   */
 4  /*   cleanup.c                                          :+:      :+:    :+:   */
 5  /*                                                    +:+ +:+         +:+     */
 6  /*   By: lfiorell <lfiorell@student.42nice.fr>      +#+  +:+       +#+        */
 7  /*                                                +#+#+#+#+#+   +#+           */
 8  /*   Created: 2025/04/03 16:53:45 by lfiorell          #+#    #+#             */
 9  /*   Updated: 2025/04/03 16:53:49 by lfiorell         ###   ########.fr       */
10  /*                                                                            */
11  /* ************************************************************************** */
12  
13  #include "philo.h"
14  
15  static void	cleanup_print_mutex(t_simulation *sim)
16  {
17  	if (sim->print_mutex)
18  	{
19  		pthread_mutex_destroy(sim->print_mutex);
20  		free(sim->print_mutex);
21  	}
22  }
23  
24  static void	cleanup_philosophers(t_simulation *sim)
25  {
26  	int	i;
27  
28  	if (sim->philosophers)
29  	{
30  		i = 0;
31  		while (i < sim->num_philosophers)
32  		{
33  			if (sim->philosophers[i])
34  				free(sim->philosophers[i]);
35  			i++;
36  		}
37  		free(sim->philosophers);
38  	}
39  }
40  
41  static void	cleanup_forks(t_simulation *sim)
42  {
43  	int	i;
44  
45  	if (sim->forks)
46  	{
47  		i = 0;
48  		while (i < sim->num_philosophers)
49  		{
50  			pthread_mutex_destroy(&sim->forks[i]);
51  			i++;
52  		}
53  		free(sim->forks);
54  	}
55  }
56  
57  static void	cleanup_death_check(t_simulation *sim)
58  {
59  	if (sim->death_check)
60  	{
61  		pthread_mutex_destroy(sim->death_check);
62  		free(sim->death_check);
63  	}
64  }
65  
66  void	cleanup(t_simulation *sim, t_arg **args)
67  {
68  	if (!sim)
69  		return ;
70  	cleanup_print_mutex(sim);
71  	cleanup_philosophers(sim);
72  	cleanup_forks(sim);
73  	cleanup_death_check(sim);
74  	free(sim);
75  	if (args)
76  		free(args);
77  }