From 810a5376b93ae1f4a0104708332e42383b3996b6 Mon Sep 17 00:00:00 2001 From: Themis Demetriades Date: Thu, 17 Oct 2024 08:55:29 +0100 Subject: [PATCH] Implement priority scheduling for condition variables --- src/threads/synch.c | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/src/threads/synch.c b/src/threads/synch.c index e1bcf9f..0cb9989 100644 --- a/src/threads/synch.c +++ b/src/threads/synch.c @@ -266,6 +266,35 @@ cond_init (struct condition *cond) list_init (&cond->waiters); } +/* Returns true iff the priority of the only thread in the first singleton + semaphore is greater than the priority of the only thread in the second + singleton semaphore. + + If used for insertion, the third argument must be a pointer to struct + list_elem for the thread being inserted, otherwise must be NULL. */ +static bool +singleton_sema_priority_greater (const struct list_elem *a, + const struct list_elem *b, + void *insertingThread) +{ + struct list_elem *te_a, *te_b; + + te_b = list_front ( + &list_entry (b, struct semaphore_elem, elem)->semaphore.waiters); + + if (insertingThread == NULL) + { + te_a = list_front ( + &list_entry (a, struct semaphore_elem, elem)->semaphore.waiters); + } + else + { + te_a = insertingThread; + } + + return thread_priority_greater (te_a, te_b, NULL); +} + /* Atomically releases LOCK and waits for COND to be signaled by some other piece of code. After COND is signaled, LOCK is reacquired before returning. LOCK must be held before calling @@ -297,7 +326,9 @@ cond_wait (struct condition *cond, struct lock *lock) ASSERT (lock_held_by_current_thread (lock)); sema_init (&waiter.semaphore, 0); - list_push_back (&cond->waiters, &waiter.elem); + list_insert_ordered (&cond->waiters, &waiter.elem, + singleton_sema_priority_greater, + &thread_current ()->elem); lock_release (lock); sema_down (&waiter.semaphore); lock_acquire (lock);