42 school project
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

85 lines
2.6 KiB

3 years ago
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* philo_threads.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: narnaud <narnaud@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/11/26 07:43:48 by narnaud #+# #+# */
/* Updated: 2022/04/11 14:52:22 by narnaud ### ########.fr */
/* */
/* ************************************************************************** */
#include "philosophers.h"
void *philos_life(void *r)
{
t_room *room;
t_param *param;
t_philo *philo;
int id;
int id_p;
room = (t_room *)r;
param = room->param;
pthread_mutex_lock(room->safe);
id = room->i;
philo = room->philos[id];
philo->eat_time = room->time;
id_p = (id + 1) % param->philo_amount;
pthread_mutex_unlock(room->safe);
while (room->running)
{
pthread_mutex_lock(philo->fork);
safe_print("%ld %d has taken a fork\n", room, id);
pthread_mutex_lock(room->philos[id_p]->fork);
safe_print("%ld %d has taken a fork\n", room, id);
safe_print("%ld %d is eating\n", room, id);
pthread_mutex_lock(philo->safe);
philo->eat_time = room->time;
pthread_mutex_unlock(philo->safe);
if (check_end(room))
{
pthread_mutex_unlock(philo->fork);
pthread_mutex_unlock(room->philos[id_p]->fork);
return (NULL);
}
usleep(param->eat_duration * 1000);
pthread_mutex_unlock(philo->fork);
pthread_mutex_unlock(room->philos[id_p]->fork);
if (check_end(room))
return (NULL);
safe_print("%ld %d is sleeping\n", room, id);
pthread_mutex_lock(philo->safe);
philo->eat_amount++;
pthread_mutex_unlock(philo->safe);
usleep(param->sleep_duration * 1000);
if (check_end(room))
return (NULL);
safe_print("%ld %d is thinking\n", room, id);
}
return (NULL);
}
void *room_clock(void *r)
{
t_room *room;
struct timeval time;
room = (t_room *)r;
while (1)
{
gettimeofday(&time, NULL);
pthread_mutex_lock(room->safe);
room->time = time.tv_sec * 1000 + time.tv_usec / 1000 - room->start_time;
if (!room->running)
{
pthread_mutex_unlock(room->safe);
return(NULL);
}
pthread_mutex_unlock(room->safe);
usleep(CLOCK_TWO);
}
return (NULL);
}