108 lines
3.2 kB
1/* ************************************************************************** */
2/* */
3/* ::: :::::::: */
4/* init.c :+: :+: :+: */
5/* +:+ +:+ +:+ */
6/* By: mleitao <marvin@42.fr> +#+ +:+ +#+ */
7/* +#+#+#+#+#+ +#+ */
8/* Created: 2026/07/02 17:47:35 by mleitao #+# #+# */
9/* Updated: 2026/07/07 01:21:52 by mleitao ### ########.fr */
10/* */
11/* ************************************************************************** */
12
13#include "codexion.h"
14#include "error.h"
15#include "sim.h"
16#include "heap.h"
17#include <stdlib.h>
18
19static int init_dongle(t_dongle *d, unsigned int id, unsigned int n,
20 unsigned int cd)
21{
22 d->id = id;
23 d->held = 0;
24 d->ticket = 0;
25 d->release_ts = -((long)cd);
26 if (heap_init(&d->queue, n) != 0)
27 return (-1);
28 if (pthread_mutex_init(&d->lock, NULL) != 0)
29 return (heap_free(&d->queue), -1);
30 if (pthread_cond_init(&d->wait, NULL) != 0)
31 {
32 pthread_mutex_destroy(&d->lock);
33 heap_free(&d->queue);
34 return (-1);
35 }
36 return (0);
37}
38
39static int init_dongles(t_dongle *d, unsigned int n, unsigned int cd)
40{
41 unsigned int i;
42
43 i = 0;
44 while (i < n)
45 {
46 if (init_dongle(&d[i], i, n, cd) != 0)
47 return (destroy_dongles(d, i), -1);
48 i++;
49 }
50 return (0);
51}
52
53static int init_locks(t_sim *sim)
54{
55 if (pthread_mutex_init(&sim->stop_lock, NULL) != 0)
56 return (-1);
57 if (pthread_mutex_init(&sim->log_lock, NULL) != 0)
58 {
59 pthread_mutex_destroy(&sim->stop_lock);
60 return (-1);
61 }
62 return (0);
63}
64
65static int init_coders(t_sim *sim, unsigned int n)
66{
67 unsigned int i;
68
69 i = 0;
70 while (i < n)
71 {
72 sim->coders[i].id = i + 1;
73 sim->coders[i].compiles_done = 0;
74 sim->coders[i].last_compile_start = 0;
75 sim->coders[i].left = &sim->dongles[i];
76 sim->coders[i].right = &sim->dongles[(i + 1) % n];
77 sim->coders[i].sim = sim;
78 if (pthread_mutex_init(&sim->coders[i].state_lock, NULL) != 0)
79 return (destroy_coders(sim->coders, i), -1);
80 i++;
81 }
82 return (0);
83}
84
85t_err init_sim(t_sim *sim, t_args args)
86{
87 unsigned int n;
88
89 n = args.v[ARG_CODERS];
90 sim->args = args;
91 sim->stop = 0;
92 sim->dongles = malloc(sizeof(t_dongle) * n);
93 sim->coders = malloc(sizeof(t_coder) * n);
94 if (!sim->dongles || !sim->coders)
95 return (free(sim->dongles), free(sim->coders), err(ERR_INIT, "", -1));
96 if (init_dongles(sim->dongles, n, args.v[ARG_COOLDOWN]) != 0)
97 return (free(sim->dongles), free(sim->coders), err(ERR_INIT, "", -1));
98 if (init_coders(sim, n) != 0)
99 return (destroy_dongles(sim->dongles, n), free(sim->dongles),
100 free(sim->coders), err(ERR_INIT, "", -1));
101 if (init_locks(sim) != 0)
102 {
103 destroy_coders(sim->coders, n);
104 destroy_dongles(sim->dongles, n);
105 return (free(sim->dongles), free(sim->coders), err(ERR_INIT, "", -1));
106 }
107 return (err(OK, "", -1));
108}