- ATM the code have a struct that contains all workers threads, mutexes and last_updated values. I need to try malloc a `WorkerState` struct and pass it to each worker thread. - Need to create a monitor thread that will iterate all workers values and watch if the last_activity_time of a worker is less than 3 seconds. If not, the monitor thread will declare it as dead.
75 lines
1.9 KiB
C
75 lines
1.9 KiB
C
/* ************************************************************************** */
|
|
/* */
|
|
/* ::: :::::::: */
|
|
/* death_monitor.c :+: :+: :+: */
|
|
/* +:+ +:+ +:+ */
|
|
/* By: ruiferna <ruiferna@student.42porto.com> +#+ +:+ +#+ */
|
|
/* +#+#+#+#+#+ +#+ */
|
|
/* Created: 2025/10/09 20:16:37 by ruiferna #+# #+# */
|
|
/* Updated: 2025/10/09 20:45:22 by ruiferna ### ########.fr */
|
|
/* */
|
|
/* ************************************************************************** */
|
|
|
|
#include "simple_philosophers.h"
|
|
|
|
#define WORKERS 4
|
|
|
|
typedef struct s_shared
|
|
{
|
|
int id;
|
|
pthread_t workers[WORKERS];
|
|
long long last_updated[WORKERS];
|
|
pthread_mutex_t workers_mutexes[WORKERS];
|
|
pthread_mutex_t mutex_id;
|
|
} t_shared;
|
|
|
|
|
|
void *worker_routine(void *arg)
|
|
{
|
|
t_shared *shared;
|
|
int worker_id;
|
|
|
|
shared = (t_shared *) arg;
|
|
pthread_mutex_lock(&shared->mutex_id);
|
|
shared->id += 1;
|
|
worker_id = shared->id;
|
|
pthread_mutex_unlock(&shared->mutex_id);
|
|
pthread_mutex_lock(&shared->workers_mutexes[worker_id]);
|
|
shared->last_updated[worker_id] = get_current_time();
|
|
pthread_mutex_lock(&shared->workers_mutexes[worker_id]);
|
|
|
|
|
|
}
|
|
int main()
|
|
{
|
|
t_shared shared;
|
|
int i;
|
|
|
|
i = 0;
|
|
while (i < WORKERS)
|
|
{
|
|
pthread_mutex_init(&shared.workers_mutexes[i], NULL);
|
|
i++;
|
|
}
|
|
pthread_mutex_init(&shared.mutex_id, NULL);
|
|
|
|
i = 0;
|
|
while (i < WORKERS)
|
|
{
|
|
if (pthread_create(&shared.workers[i], NULL, worker_routine, &shared) != 0)
|
|
{
|
|
perror("pthread_create");
|
|
exit(EXIT_FAILURE);
|
|
}
|
|
i++;
|
|
}
|
|
|
|
i = 0;
|
|
while (i < WORKERS)
|
|
{
|
|
pthread_join(shared.workers[i], NULL);
|
|
i++;
|
|
}
|
|
|
|
return (0);
|
|
} |