aboutsummaryrefslogtreecommitdiff
path: root/philo_one/philo.c
blob: c585e34f160138d29ede9a745978fd24d402ac67 (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
75
76
77
78
79
80
81
82
83
84
85
86
/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   philo.c                                            :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: cacharle <marvin@42.fr>                    +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2020/02/09 23:47:14 by cacharle          #+#    #+#             */
/*   Updated: 2020/02/14 01:38:45 by cacharle         ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "philo_one.h"

t_philo				*philos_new(int num)
{
	int		i;
	t_philo	*philos;

	if (num < 0)
		return (NULL);
	if ((philos = (t_philo*)h_calloc(num + 1, sizeof(t_philo))) == NULL)
		return (NULL);
	i = -1;
	while (++i < num)
	{
		philos[i].id = i + 1;
		philos[i].alive = FALSE;
	}
	return (philos);
}

void				philos_destroy(t_philo *philos, int num)
{
	(void)num;
	if (philos == NULL)
		return ;
	free(philos);
}

t_bool	philos_start(t_philo *philos, t_routine_arg *routine_args, int num)
{
	int				i;

	i = -1;
	while (++i < num)
	{
		philos[i].alive = TRUE;
		if (pthread_create(&philos[i].thread, NULL, &routine_philo, (void*)(routine_args + i)) == -1)
			return (FALSE);
	}
	return (TRUE);
}

void	philos_join(t_philo *philos, int num)
{
	int	i;

	i = -1;
	while (++i < num)
	{
		if (philos[i].alive)
		{
			philos[i].alive = FALSE;
			/* pthread_join(philos[i].thread, NULL); */
		}
	}
}

t_bool	philos_starved(t_philo *philos, int num)
{
	int	i;

	i = -1;
	while (++i < num)
	{
		if (!philos[i].alive)
		{
			i = -1;
			while (++i < num)
				philos[i].alive = FALSE;
			return (TRUE);
		}
	}
	return (FALSE);
}