96 lines
2.6 kB
1/* ************************************************************************** */
2/* */
3/* ::: :::::::: */
4/* dongle.c :+: :+: :+: */
5/* +:+ +:+ +:+ */
6/* By: mleitao <marvin@42.fr> +#+ +:+ +#+ */
7/* +#+#+#+#+#+ +#+ */
8/* Created: 2026/07/07 01:27:25 by mleitao #+# #+# */
9/* Updated: 2026/07/11 20:08:21 by mleitao ### ########.fr */
10/* */
11/* ************************************************************************** */
12
13#include "codexion.h"
14#include "dongle.h"
15#include "heap.h"
16#include "state.h"
17#include "timer.h"
18#include <pthread.h>
19
20static long request_key(t_coder *c, t_dongle *d)
21{
22 long key;
23
24 if (c->sim->args.scheduler == SCHD_FIFO)
25 {
26 key = d->ticket;
27 d->ticket++;
28 }
29 else
30 {
31 key = c->last_compile_start + c->sim->args.v[ARG_BURNOUT];
32 }
33 return (key);
34}
35
36static int can_take(t_coder *c, t_dongle *d)
37{
38 if (d->held)
39 return (0);
40 if (heap_peek(&d->queue).coder_id != c->id)
41 return (0);
42 if (elapsed_ms(c->sim->start_ms) < d->release_ts
43 + (long)c->sim->args.v[ARG_COOLDOWN])
44 return (0);
45 return (1);
46}
47
48static void wait_turn(t_coder *c, t_dongle *d)
49{
50 long avail;
51 struct timespec ts;
52
53 avail = d->release_ts + (long)c->sim->args.v[ARG_COOLDOWN];
54 if (!d->held && heap_peek(&d->queue).coder_id == c->id
55 && elapsed_ms(c->sim->start_ms) < avail)
56 {
57 ms_to_timespec(c->sim->start_ms + avail, &ts);
58 pthread_cond_timedwait(&d->wait, &d->lock, &ts);
59 }
60 else
61 {
62 pthread_cond_wait(&d->wait, &d->lock);
63 }
64}
65
66int dongle_acquire(t_coder *c, t_dongle *d)
67{
68 t_req r;
69
70 pthread_mutex_lock(&d->lock);
71 r.key = request_key(c, d);
72 r.coder_id = c->id;
73 heap_push(&d->queue, r);
74 while (!sim_stopped(c->sim) && !can_take(c, d))
75 wait_turn(c, d);
76 if (sim_stopped(c->sim))
77 {
78 heap_remove(&d->queue, c->id);
79 pthread_mutex_unlock(&d->lock);
80 return (-1);
81 }
82 heap_remove(&d->queue, c->id);
83 d->held = 1;
84 pthread_mutex_unlock(&d->lock);
85 log_state(c->sim, c->id, MSG_TAKEN);
86 return (0);
87}
88
89void dongle_release(t_coder *c, t_dongle *d)
90{
91 pthread_mutex_lock(&d->lock);
92 d->held = 0;
93 d->release_ts = elapsed_ms(c->sim->start_ms);
94 pthread_cond_broadcast(&d->wait);
95 pthread_mutex_unlock(&d->lock);
96}