42_Philosopher/print.c

67 lines
1.3 KiB
C
Raw Normal View History

2023-04-13 09:00:39 -04:00
#include "philo.h"
#include <bits/pthreadtypes.h>
#include <pthread.h>
2023-04-25 10:30:21 -04:00
#include <stdbool.h>
2023-04-13 09:00:39 -04:00
#include <stddef.h>
#include "./time.h"
2023-04-25 10:30:21 -04:00
#include "./utils/utils.h"
2023-04-13 09:00:39 -04:00
2023-04-19 07:53:50 -04:00
static void print(t_data *data, size_t id, char *str)
2023-04-13 09:00:39 -04:00
{
size_t time;
2023-04-25 10:30:21 -04:00
bool stop;
2023-04-13 09:00:39 -04:00
2023-04-25 10:30:21 -04:00
time = get_time();
pthread_mutex_lock(&data->print_mutex);
2023-04-19 07:53:50 -04:00
pthread_mutex_lock(&data->stop_mutex);
2023-04-25 10:30:21 -04:00
stop = data->stop;
pthread_mutex_unlock(&data->stop_mutex);
if (stop == false)
2023-04-19 07:53:50 -04:00
{
2023-04-25 10:30:21 -04:00
ft_putnum(time, 7);
ft_putchar(' ');
ft_putnum(id + 1, 3);
ft_putchar(' ');
ft_putstr(str);
ft_putchar('\n');
2023-04-19 07:53:50 -04:00
}
pthread_mutex_unlock(&data->print_mutex);
2023-04-13 09:00:39 -04:00
}
void print_take_a_fork(t_philo *philo)
{
2023-04-19 07:53:50 -04:00
print(philo->data, philo->id, "has taken a fork");
2023-04-13 09:00:39 -04:00
}
void print_eating(t_philo *philo)
{
2023-04-19 07:53:50 -04:00
print(philo->data, philo->id, "is eating");
2023-04-13 09:00:39 -04:00
}
void print_sleeping(t_philo *philo)
{
2023-04-19 07:53:50 -04:00
print(philo->data, philo->id, "is sleeping");
2023-04-13 09:00:39 -04:00
}
void print_thinking(t_philo *philo)
{
2023-04-19 07:53:50 -04:00
print(philo->data, philo->id, "is thinking");
2023-04-13 09:00:39 -04:00
}
void print_died(t_philo *philo)
{
2023-04-25 10:30:21 -04:00
t_data *data;
size_t time;
data = philo->data;
time = get_time();
pthread_mutex_lock(&data->print_mutex);
ft_putnum(time, 7);
ft_putchar(' ');
ft_putnum(philo->id + 1, 3);
ft_putchar(' ');
ft_putstr("died");
ft_putchar('\n');
pthread_mutex_unlock(&data->print_mutex);
2023-04-13 09:00:39 -04:00
}