tgrekov-philosophers
HIVE philosophers July 2024
Loading...
Searching...
No Matches
setup.c
Go to the documentation of this file.
1/* ************************************************************************** */
2/* */
3/* ::: :::::::: */
4/* setup.c :+: :+: :+: */
5/* +:+ +:+ +:+ */
6/* By: tgrekov <tgrekov@student.hive.fi> +#+ +:+ +#+ */
7/* +#+#+#+#+#+ +#+ */
8/* Created: 2024/08/02 07:21:43 by tgrekov #+# #+# */
9/* Updated: 2024/08/02 07:39:01 by tgrekov ### ########.fr */
10/* */
11/* ************************************************************************** */
12
20#include <stdlib.h>
21#include "../philosopher/philo.h"
22
30static int allocate(t_global *global, t_thread **thread)
31{
32 *thread = 0;
33 global->forks = malloc(sizeof(pthread_mutex_t) * global->opt.n);
34 if (!global->forks)
35 return (1);
36 *thread = malloc(sizeof(t_thread) * global->opt.n);
37 if (!*thread)
38 return (1);
39 return (0);
40}
41
49static int initialize(t_global *global, t_thread *thread)
50{
51 int i;
52
53 i = 0;
54 while (i < global->opt.n && !pthread_mutex_init(&global->forks[i], 0))
55 i++;
56 if (i == global->opt.n)
57 {
58 if (!global->opt.eat_n)
59 return (0);
60 i = 0;
61 while (i < global->opt.n && !pthread_mutex_init(&thread[i].full, 0))
62 i++;
63 if (i == global->opt.n)
64 return (0);
65 i++;
66 while (i--)
67 pthread_mutex_destroy(&thread[i].full);
68 i = global->opt.n - 1;
69 }
70 i++;
71 while (i--)
72 pthread_mutex_destroy(&global->forks[i]);
73 return (1);
74}
75
84int setup(t_global *global, t_thread **thread)
85{
86 if (allocate(global, thread))
87 return (1);
88 if (pthread_mutex_init(&global->printing, 0))
89 return (1);
90 if (!pthread_mutex_init(&global->end_mutex, 0))
91 {
92 if (!initialize(global, *thread))
93 return (0);
94 pthread_mutex_destroy(&global->end_mutex);
95 }
96 pthread_mutex_destroy(&global->printing);
97 return (1);
98}
static int initialize(t_global *global, t_thread *thread)
Initialize forks and eating quota mutexes.
Definition setup.c:49
static int allocate(t_global *global, t_thread **thread)
Allocate fork and thread arrays.
Definition setup.c:30
int setup(t_global *global, t_thread **thread)
Allocate fork array and thread structure, initialize mutexes.
Definition setup.c:84