diff --git a/src/threads/synch.c b/src/threads/synch.c index 078f142..b588656 100644 --- a/src/threads/synch.c +++ b/src/threads/synch.c @@ -268,22 +268,49 @@ struct semaphore_elem /* Function that compares the two *semaphores* associated with the provided list_elem structures. [i.e., takes list_elem of semaphore_elem, and] Returns true if the thread associated with the semaphore associated with a_ - has a higher priority than that of b_. */ + has a higher priority than that of b_. + + If aux is provided, then it is a pointer to an integer representing the + priority of the first semaphore. This is useful when the thread has not been + sema'd down yet. */ static bool sema_priority_more(const struct list_elem *a_, const struct list_elem *b_, - void *aux UNUSED) + void *aux) { - struct semaphore_elem *a = list_entry(a_, struct semaphore_elem, elem); + int a_priority, b_priority; + + /* If an aux is provided, then use it as the priority of the first semaphore. + Otherwise, get the priority of the first semaphore. */ + if (aux != NULL) + a_priority = *(int *) aux; + else + { + struct semaphore_elem *a = list_entry(a_, struct semaphore_elem, elem); + + /* If waiters list is empty, return false (i.e., a has lower priority) */ + if (list_empty(&a->semaphore.waiters)) + return false; + + /* Otherwise, get the thread with the highest priority from the waiters + list. By design, this is the first one in the list (See sema_down). */ + struct thread *a_thread = + list_entry(list_front(&a->semaphore.waiters), struct thread, elem); + + a_priority = a_thread->priority; + } + struct semaphore_elem *b = list_entry(b_, struct semaphore_elem, elem); - /* Get the highest priority thread from the waiters list of each semaphore. By - design, this is the first element in the list (See sema_down). */ - struct thread *a_thread = - list_entry(list_front(&a->semaphore.waiters), struct thread, elem); + /* If waiters list is empty, return true (i.e., a has higher priority) */ + if (list_empty(&b->semaphore.waiters)) + return true; + struct thread *b_thread = list_entry(list_front(&b->semaphore.waiters), struct thread, elem); - return a_thread->priority > b_thread->priority; + b_priority = b_thread->priority; + + return a_priority > b_priority; } /* Initializes condition variable COND. A condition variable