From 91cef4d650922cc341b7d40fdd7038cde333039e Mon Sep 17 00:00:00 2001 From: sBubshait Date: Wed, 6 Nov 2024 15:36:56 +0000 Subject: [PATCH] Refactor lock release and sema up to remove unnecessary code --- src/threads/synch.c | 28 ++++++++++++++++------------ 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/src/threads/synch.c b/src/threads/synch.c index 09fc71f..d706d19 100644 --- a/src/threads/synch.c +++ b/src/threads/synch.c @@ -113,28 +113,33 @@ void sema_up (struct semaphore *sema) { enum intr_level old_level; + bool thread_unblocked = false; /* Flag to track if any thread was woken up. */ ASSERT (sema != NULL); old_level = intr_disable (); if (!list_empty (&sema->waiters)) - { - /* Enforces wake-up of the highest priority thread waiting for the - semaphore. */ - struct list_elem *e = list_max (&sema->waiters, priority_less, NULL); - list_remove (e); - thread_unblock (list_entry (e, struct thread, elem)); - } + { + /* Enforces wake-up of the highest priority thread waiting for the + semaphore. */ + struct list_elem *e = list_max (&sema->waiters, priority_less, NULL); + list_remove (e); + thread_unblock (list_entry (e, struct thread, elem)); + thread_unblocked = true; + } sema->value++; intr_set_level (old_level); /* Yields the CPU in case the thread that has been woken up has a higher priority that the current running thread, including the case when called within an interrupt handler. */ - if (intr_context ()) - intr_yield_on_return (); - else - thread_yield (); + if (thread_unblocked) + { + if (intr_context ()) + intr_yield_on_return (); + else + thread_yield (); + } } static void sema_test_helper (void *sema_); @@ -347,7 +352,6 @@ lock_release (struct lock *lock) lock->holder = NULL; sema_up (&lock->semaphore); - thread_yield (); } /* Returns true if the current thread holds LOCK, false