Add time_to_think to increase survivability trunk
authorLukas Jiriste <ljiriste@student.42prague.com>
Thu, 3 Oct 2024 07:15:55 +0000 (09:15 +0200)
committerLukas Jiriste <ljiriste@student.42prague.com>
Thu, 3 Oct 2024 07:30:30 +0000 (09:30 +0200)
I thought that the program should be a tool to demonstrate the dangers
in parallel computing. Hence I let the user wholly define what
philosophers can do.
This point of view has however failed me multiple times during
evaluation... This (and a couple of conversations) led me to believe the
only way to pass is to add another element - the time_to_think.

When odd number of philosophers is entered and the time_to_sleep is too
low, the time_to_think is set to such a value that philosophers can
share the forks fairly.

philo/parsing.c
philo/philo.c
philo/philo.h

index ec9a39f259b8a3524300668d382b3f2ba363518f..90d6c5c0904849477cd4d2b0aa495c4d6883c7f3 100644 (file)
@@ -15,6 +15,8 @@
 #include <stddef.h>
 #include <stdlib.h>
 
+#define RESERVE 100
+
 int    is_sane(t_settings *settings)
 {
        return (settings->philo_count > 0);
@@ -33,6 +35,13 @@ int  parse_input(t_settings *settings, int argc, char **argv)
        {
                return (1);
        }
+       if (settings->philo_count % 2
+               && 3 * settings->time_to_eat < settings->time_to_die
+               && 2 * settings->time_to_eat > settings->time_to_sleep)
+               settings->time_to_think = 2 * settings->time_to_eat
+                       - settings->time_to_sleep + RESERVE;
+       else
+               settings->time_to_think = 0;
        if (argc == 6)
        {
                if (parse_arg_uint(&settings->min_eat_num, argv[5]))
index f0f52fcb7150ae3281548c5d9d01c0d9821b766a..e1fe1f00257fadfedc6ea2f2f57510422587c69a 100644 (file)
@@ -15,7 +15,8 @@
 
 static void    philo_think(t_philo *philo)
 {
-       report(philo, "is thinking");
+       if (!report(philo, "is thinking"))
+               usleep(philo->settings->time_to_think);
        return ;
 }
 
@@ -82,13 +83,14 @@ void        *be_a_philosopher(void *void_philo)
 {
        t_philo *const  philo = void_philo;
 
+       report(philo, "is thinking");
        if (philo->id % 2)
                usleep(1000);
        while (!end(philo->settings))
        {
-               philo_think(philo);
                philo_eat(philo);
                philo_sleep(philo);
+               philo_think(philo);
        }
        return (NULL);
 }
index 8eeed5894459834160b2d9dc4bfbd1c22a29467b..698d2b641eb6dc0ce3adb0f4b623ae2282f460fa 100644 (file)
@@ -35,6 +35,7 @@ typedef struct s_settings
        useconds_t              time_to_die;
        useconds_t              time_to_eat;
        useconds_t              time_to_sleep;
+       useconds_t              time_to_think;
        size_t                  philo_count;
        struct timeval  start;
        t_mutex                 terminal_lock;