Change the order of waiting for term and checking
authorLukas Jiriste <ljiriste@student.42prague.com>
Thu, 30 May 2024 13:00:56 +0000 (15:00 +0200)
committerLukas Jiriste <ljiriste@student.42prague.com>
Thu, 30 May 2024 13:00:56 +0000 (15:00 +0200)
This is done so that a philosopher truly cannot write to terminal after
it dies. Before this commit, a philosopher that is alive would wait for
term semaphore. Meanwhile something could change his state to not alive
but he could then get the semaphore and print anyway.

I thought about having the condition inside as well as on the outside
of the sem_wait. But having it just after the sem_wait should be
alright.

philo_bonus/helpers.c

index c7e54b0cb5f172c305bb485bd75ef7b3f6e9d94e..44c7980f6ee513f045ee48c651f4504942c9a57a 100644 (file)
@@ -6,7 +6,7 @@
 /*   By: ljiriste <marvin@42.fr>                    +#+  +:+       +#+        */
 /*                                                +#+#+#+#+#+   +#+           */
 /*   Created: 2024/05/09 09:13:40 by ljiriste          #+#    #+#             */
-/*   Updated: 2024/05/24 15:32:49 by ljiriste         ###   ########.fr       */
+/*   Updated: 2024/05/30 14:45:17 by ljiriste         ###   ########.fr       */
 /*                                                                            */
 /* ************************************************************************** */
 
@@ -43,12 +43,10 @@ void        print_timestamp(t_philo *philo, const char *str)
 
 void   report(t_philo *philo, const char *str)
 {
+       sem_wait(philo->semaphores.term);
        if (is_alive(philo))
-       {
-               sem_wait(philo->semaphores.term);
                print_timestamp(philo, str);
-               sem_post(philo->semaphores.term);
-       }
+       sem_post(philo->semaphores.term);
        return ;
 }