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.

55 lines
2.0 KiB

3 years ago
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* philo_threads.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: narnaud <narnaud@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/11/26 07:43:48 by narnaud #+# #+# */
3 years ago
/* Updated: 2022/05/16 17:51:21 by narnaud ### ########.fr */
3 years ago
/* */
/* ************************************************************************** */
#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];
3 years ago
philo->eat_time = gettime();
3 years ago
id_p = (id + 1) % param->philo_amount;
while (room->running)
{
3 years ago
pthread_mutex_unlock(room->safe);
3 years ago
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);
3 years ago
if (!safe_wait(room, gettime(), param->eat_duration * 1000))
3 years ago
return (NULL);
pthread_mutex_unlock(philo->fork);
pthread_mutex_unlock(room->philos[id_p]->fork);
pthread_mutex_lock(philo->safe);
3 years ago
philo->eat_time = gettime();
3 years ago
philo->eat_amount++;
pthread_mutex_unlock(philo->safe);
3 years ago
safe_print("%ld %d is sleeping\n", room, id);
if (!safe_wait(room, gettime(), param->sleep_duration * 1000))
3 years ago
return (NULL);
safe_print("%ld %d is thinking\n", room, id);
pthread_mutex_lock(room->safe);
}
3 years ago
pthread_mutex_unlock(room->safe);
3 years ago
return (NULL);
}