aboutsummaryrefslogtreecommitdiff
path: root/philo_three/src/child.c
diff options
context:
space:
mode:
authorCharles Cabergs <me@cacharle.xyz>2021-01-10 10:54:04 +0100
committerCharles Cabergs <me@cacharle.xyz>2021-01-10 10:54:04 +0100
commiteb2cfb574efafcf2c3c6200d1cd2de700ec8ddfb (patch)
treeefff80bbbc2157979eaae006f6835d020062dba9 /philo_three/src/child.c
parent802ea8347d1ceb7a02cf279359b3b101106fab94 (diff)
downloadphilosophers-eb2cfb574efafcf2c3c6200d1cd2de700ec8ddfb.tar.gz
philosophers-eb2cfb574efafcf2c3c6200d1cd2de700ec8ddfb.tar.bz2
philosophers-eb2cfb574efafcf2c3c6200d1cd2de700ec8ddfb.zip
Fixing bad performance at school by adding more delay to the death checking loop, Added mutex/semaphore to protect against eating and dying at the same time
Diffstat (limited to 'philo_three/src/child.c')
-rw-r--r--philo_three/src/child.c23
1 files changed, 14 insertions, 9 deletions
diff --git a/philo_three/src/child.c b/philo_three/src/child.c
index 641b82d..63ec3e4 100644
--- a/philo_three/src/child.c
+++ b/philo_three/src/child.c
@@ -6,7 +6,7 @@
/* By: cacharle <me@cacharle.xyz> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/09/30 14:36:16 by cacharle #+# #+# */
-/* Updated: 2021/01/09 15:59:00 by charles ### ########.fr */
+/* Updated: 2021/01/10 10:39:19 by cacharle ### ########.fr */
/* */
/* ************************************************************************** */
@@ -14,13 +14,13 @@
void *routine_death(t_philo *philo)
{
- t_time current;
-
- current = h_time_now();
- while (current - philo->time_last_eat < philo->conf->timeout_death)
+ while (true)
{
- current = h_time_now();
- usleep(1000);
+ sem_wait(philo->sem_eat);
+ if (h_time_now() - philo->time_last_eat > philo->conf->timeout_death)
+ break ;
+ sem_post(philo->sem_eat);
+ usleep(2000);
}
event_die(philo);
return (NULL);
@@ -37,7 +37,6 @@ void st_child_loop(t_philo *philo)
event_take_fork(philo);
event_take_fork(philo);
sem_post(philo->sem_grab);
- philo->time_last_eat = h_time_now();
event_eat(philo);
eat_counter++;
if (philo->conf->meal_num != -1 && eat_counter == philo->conf->meal_num)
@@ -51,10 +50,13 @@ void st_child_loop(t_philo *philo)
}
}
+#define PHILO_SEM_EAT_PREFIX "semaphore_philo_three_eat_"
+
pid_t child_start(t_philo *philo)
{
pthread_t thread_death;
pid_t pid;
+ const char *sem_eat_name;
if ((pid = fork()) == -1)
return (-1);
@@ -66,10 +68,13 @@ pid_t child_start(t_philo *philo)
philo->sem_meal_num = sem_open(PHILO_SEM_MEAL_NUM_NAME, 0);
philo->sem_start = sem_open(PHILO_SEM_START_NAME, 0);
philo->sem_grab = sem_open(PHILO_SEM_GRAB_NAME, 0);
+ sem_eat_name = philo_sem_eat_name(PHILO_SEM_EAT_PREFIX, philo->id);
+ sem_unlink(sem_eat_name);
+ philo->sem_eat = sem_open(sem_eat_name, O_CREAT | O_EXCL, 0700, 1);
+ sem_wait(philo->sem_start);
philo->time_last_eat = h_time_now();
pthread_create(&thread_death, NULL, (t_routine)routine_death, philo);
pthread_detach(thread_death);
- sem_wait(philo->sem_start);
st_child_loop(philo);
exit(0);
}