​codexion /
src / sim / run.c
60 commits
11-07-2026
58 lines 1.7 kB
 1/* ************************************************************************** */
 2/*                                                                            */
 3/*                                                        :::      ::::::::   */
 4/*   run.c                                              :+:      :+:    :+:   */
 5/*                                                    +:+ +:+         +:+     */
 6/*   By: mleitao <marvin@42.fr>                     +#+  +:+       +#+        */
 7/*                                                +#+#+#+#+#+   +#+           */
 8/*   Created: 2026/07/07 02:09:24 by mleitao           #+#    #+#             */
 9/*   Updated: 2026/07/11 20:09:26 by mleitao          ###   ########.fr       */
10/*                                                                            */
11/* ************************************************************************** */
12
13#include "codexion.h"
14#include "state.h"
15#include "sim.h"
16#include "timer.h"
17
18static void	abort_run(t_sim *sim, unsigned int created)
19{
20	unsigned int	i;
21
22	sim_set_stop(sim);
23	wake_all(sim);
24	i = 0;
25	while (i < created)
26	{
27		pthread_join(sim->coders[i].thread, NULL);
28		i++;
29	}
30}
31
32int	run_sim(t_sim *sim)
33{
34	unsigned int	n;
35	unsigned int	i;
36	pthread_t		monitor;
37
38	n = sim->args.v[ARG_CODERS];
39	sim->start_ms = now_ms();
40	i = 0;
41	while (i < n)
42	{
43		if (pthread_create(&sim->coders[i].thread, NULL,
44				coder_routine, &sim->coders[i]) != 0)
45			return (abort_run(sim, i), -1);
46		i++;
47	}
48	if (pthread_create(&monitor, NULL, monitor_routine, sim) != 0)
49		return (abort_run(sim, n), -1);
50	i = 0;
51	while (i < n)
52	{
53		pthread_join(sim->coders[i].thread, NULL);
54		i++;
55	}
56	pthread_join(monitor, NULL);
57	return (0);
58}