aboutsummaryrefslogtreecommitdiff
path: root/philo_one/src/forks.c
blob: 84bc0fd761206e19240c11bb0c59c5a2b30db09a (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
/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   forks.c                                            :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: cacharle <marvin@42.fr>                    +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2020/02/09 23:46:40 by cacharle          #+#    #+#             */
/*   Updated: 2021/01/10 11:29:09 by cacharle         ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "philo_one.h"

pthread_mutex_t	*forks_new(long int num)
{
	long int		i;
	pthread_mutex_t	*forks;

	if ((forks = malloc(num * sizeof(pthread_mutex_t))) == NULL)
		return (NULL);
	i = -1;
	while (++i < num)
	{
		if (pthread_mutex_init(&forks[i], NULL) != 0)
		{
			forks_destroy(forks, i);
			return (NULL);
		}
	}
	return (forks);
}

void			forks_destroy(pthread_mutex_t *forks, long int num)
{
	if (forks == NULL)
		return ;
	while (num-- > 0)
		pthread_mutex_destroy(&forks[num]);
	free(forks);
}