​codexion /
src / sim / coder.c
60 commits
06-08-2026
85 lines 2.4 kB
 1/* ************************************************************************** */
 2/*                                                                            */
 3/*                                                        :::      ::::::::   */
 4/*   coder.c                                            :+:      :+:    :+:   */
 5/*                                                    +:+ +:+         +:+     */
 6/*   By: mleitao <marvin@42.fr>                     +#+  +:+       +#+        */
 7/*                                                +#+#+#+#+#+   +#+           */
 8/*   Created: 2026/07/07 01:43:01 by mleitao           #+#    #+#             */
 9/*   Updated: 2026/07/11 20:09:17 by mleitao          ###   ########.fr       */
10/*                                                                            */
11/* ************************************************************************** */
12
13#include "codexion.h"
14#include "dongle.h"
15#include "state.h"
16#include "sim.h"
17#include "timer.h"
18#include <unistd.h>
19
20static int	precise_sleep(t_coder *c, unsigned int dur)
21{
22	long	target;
23
24	target = elapsed_ms(c->sim->start_ms) + (long)dur;
25	while (elapsed_ms(c->sim->start_ms) < target)
26	{
27		if (sim_stopped(c->sim))
28			return (-1);
29		usleep(200);
30	}
31	return (0);
32}
33
34static int	do_compile(t_coder *c)
35{
36	if (take_dongles(c) != 0)
37		return (-1);
38	pthread_mutex_lock(&c->state_lock);
39	c->last_compile_start = elapsed_ms(c->sim->start_ms);
40	pthread_mutex_unlock(&c->state_lock);
41	log_state(c->sim, c->id, MSG_COMPILE);
42	if (precise_sleep(c, c->sim->args.v[ARG_COMPILE]) != 0)
43		return (put_dongles(c), -1);
44	pthread_mutex_lock(&c->state_lock);
45	c->compiles_done++;
46	pthread_mutex_unlock(&c->state_lock);
47	put_dongles(c);
48	return (0);
49}
50
51static int	rest_state(t_coder *c, unsigned int arg, const char *msg)
52{
53	if (sim_stopped(c->sim))
54		return (-1);
55	log_state(c->sim, c->id, msg);
56	return (precise_sleep(c, c->sim->args.v[arg]));
57}
58
59void	*coder_routine(void *arg)
60{
61	t_coder	*c;
62
63	c = (t_coder *)arg;
64	if (c->left == c->right)
65	{
66		if (dongle_acquire(c, c->left) == 0)
67		{
68			while (!sim_stopped(c->sim))
69				usleep(500);
70			dongle_release(c, c->left);
71		}
72		return (NULL);
73	}
74	if (c->id % 2 == 0)
75		precise_sleep(c, c->sim->args.v[ARG_COMPILE] / 2);
76	while (!sim_stopped(c->sim))
77	{
78		if (do_compile(c) != 0)
79			break ;
80		if (rest_state(c, ARG_DEBUG, MSG_DEBUG) != 0)
81			break ;
82		rest_state(c, ARG_REFACTOR, MSG_REFACTOR);
83	}
84	return (NULL);
85}