From 0d6fb2f1675d1dec50c8618e0751491c06edf939 Mon Sep 17 00:00:00 2001 From: sBubshait Date: Thu, 17 Oct 2024 07:15:10 +0100 Subject: [PATCH] Update sema_up to yield CPU if unblocked has higher priority --- src/threads/synch.c | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/src/threads/synch.c b/src/threads/synch.c index 39575ca..ffdb588 100644 --- a/src/threads/synch.c +++ b/src/threads/synch.c @@ -114,11 +114,22 @@ sema_up (struct semaphore *sema) ASSERT (sema != NULL); old_level = intr_disable (); - if (!list_empty (&sema->waiters)) - thread_unblock (list_entry (list_pop_front (&sema->waiters), - struct thread, elem)); + + /* Wake up (unblock) the highest priority thread from the waiters list */ + struct thread *t = NULL; + if (!list_empty (&sema->waiters)) + { + t = list_entry (list_pop_front (&sema->waiters), struct thread, elem); + thread_unblock (t); + } + sema->value++; intr_set_level (old_level); + + /* If the unblocked thread has higher priority than the current running thread + then yield the CPU to the unblocked thread */ + if (!intr_context() && t != NULL && t->priority > thread_get_priority ()) + thread_yield (); } static void sema_test_helper (void *sema_);