Merge branch 'refactor-semaphore' into 'master'

Refactor synch.c to remove code duplication in lock release

See merge request lab2425_autumn/pintos_22!23
This commit is contained in:
Dias Alberto, Ethan
2024-11-06 16:42:26 +00:00

View File

@@ -113,28 +113,33 @@ void
sema_up (struct semaphore *sema) sema_up (struct semaphore *sema)
{ {
enum intr_level old_level; enum intr_level old_level;
bool thread_unblocked = false; /* Flag to track if any thread was woken up. */
ASSERT (sema != NULL); ASSERT (sema != NULL);
old_level = intr_disable (); old_level = intr_disable ();
if (!list_empty (&sema->waiters)) if (!list_empty (&sema->waiters))
{ {
/* Enforces wake-up of the highest priority thread waiting for the /* Enforces wake-up of the highest priority thread waiting for the
semaphore. */ semaphore. */
struct list_elem *e = list_max (&sema->waiters, priority_less, NULL); struct list_elem *e = list_max (&sema->waiters, priority_less, NULL);
list_remove (e); list_remove (e);
thread_unblock (list_entry (e, struct thread, elem)); thread_unblock (list_entry (e, struct thread, elem));
} thread_unblocked = true;
}
sema->value++; sema->value++;
intr_set_level (old_level); intr_set_level (old_level);
/* Yields the CPU in case the thread that has been woken up has a higher /* 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 priority that the current running thread, including the case when called
within an interrupt handler. */ within an interrupt handler. */
if (intr_context ()) if (thread_unblocked)
intr_yield_on_return (); {
else if (intr_context ())
thread_yield (); intr_yield_on_return ();
else
thread_yield ();
}
} }
static void sema_test_helper (void *sema_); static void sema_test_helper (void *sema_);
@@ -347,7 +352,6 @@ lock_release (struct lock *lock)
lock->holder = NULL; lock->holder = NULL;
sema_up (&lock->semaphore); sema_up (&lock->semaphore);
thread_yield ();
} }
/* Returns true if the current thread holds LOCK, false /* Returns true if the current thread holds LOCK, false