Add priority_less for comparing threads based on priority and Refactor sema up to use list_max for clarity

This commit is contained in:
sBubshait
2024-10-25 16:04:55 +01:00
parent 30ab3ae861
commit c2414ec54d

View File

@@ -32,6 +32,10 @@
#include "threads/interrupt.h" #include "threads/interrupt.h"
#include "threads/thread.h" #include "threads/thread.h"
static bool
priority_less (const struct list_elem *a_, const struct list_elem *b_,
void *aux UNUSED);
/* Initializes semaphore SEMA to VALUE. A semaphore is a /* Initializes semaphore SEMA to VALUE. A semaphore is a
nonnegative integer along with two atomic operators for nonnegative integer along with two atomic operators for
manipulating it: manipulating it:
@@ -117,7 +121,7 @@ sema_up (struct semaphore *sema)
{ {
/* 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_min (&sema->waiters, priority_more, 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));
} }
@@ -364,6 +368,19 @@ struct semaphore_elem
struct semaphore semaphore; /* This semaphore. */ struct semaphore semaphore; /* This semaphore. */
}; };
/* Function that compares the two threads associated with the provided
pointers to their 'elem' member. Returns true if the thread associated
with a_ has a lower priority than that of b_. */
static bool
priority_less (const struct list_elem *a_, const struct list_elem *b_,
void *aux UNUSED)
{
struct thread *a = list_entry (a_, struct thread, elem);
struct thread *b = list_entry (b_, struct thread, elem);
return a->priority < b->priority;
}
/* Function that compares the two *semaphores* associated with the provided /* Function that compares the two *semaphores* associated with the provided
list_elem structures. [i.e., takes list_elem of semaphore_elem, and] list_elem structures. [i.e., takes list_elem of semaphore_elem, and]
Returns true if the thread associated with the semaphore associated with a_ Returns true if the thread associated with the semaphore associated with a_