aboutsummaryrefslogtreecommitdiff
path: root/philo_one/src/main.c
blob: 5ee4ba539e864d36a49fec41ed840c83a30f03ac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   main.c                                             :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: cacharle <marvin@42.fr>                    +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2019/11/24 05:53:02 by cacharle          #+#    #+#             */
/*   Updated: 2021/01/01 13:43:46 by charles          ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "philo_one.h"

static int	st_setup(
	t_philo_conf *conf,
	t_philo **philos,
	pthread_mutex_t **forks)
{
	if ((*forks = forks_new(conf->philo_num)) == NULL)
		return (1);
	if ((*philos = philos_new(conf, *forks)) == NULL)
	{
		forks_destroy(*forks, conf->philo_num);
		return (1);
	}
	if (pthread_mutex_init(&conf->mutex_stdout, NULL) != 0)
	{
		forks_destroy(*forks, conf->philo_num);
		free(*philos);
		return (1);
	}
	if (pthread_mutex_init(&conf->mutex_meal_num_finished_counter, NULL) != 0)
	{
		forks_destroy(*forks, conf->philo_num);
		free(*philos);
		pthread_mutex_destroy(&conf->mutex_stdout);
		return (1);
	}
	conf->all_alive = true;
	conf->meal_num_finished_counter = 0;
	return (0);
}

int			main(int argc, char **argv)
{
	t_philo_conf	conf;
	t_philo			*philos;
	pthread_mutex_t	*forks;

	if (!parse_args((t_philo_args*)&conf, argc, argv))
		return (1);
	if (conf.philo_num == 0 || conf.meal_num == 0)
		return (0);
	if (st_setup(&conf, &philos, &forks) != 0)
		return (1);
	if (!philos_start(philos, conf.philo_num))
	{
		forks_destroy(forks, conf.philo_num);
		free(philos);
		return (1);
	}
	while (!philo_finished(&conf))
		;
		/* if (conf.meal_num != -1 && conf.meal_num_finished_counter == conf.philo_num) */
		/* 	break; */
	/* conf.all_alive = false; */
	philos_detach(philos, conf.philo_num);
	forks_destroy(forks, conf.philo_num);
	pthread_mutex_destroy(&conf.mutex_stdout);
	pthread_mutex_destroy(&conf.mutex_meal_num_finished_counter);
	free(philos);
	return (0);
}