Skip to content

Commit

Permalink
cleaning
Browse files Browse the repository at this point in the history
Signed-off-by: Zach Puller <zpuller@nvidia.com>
  • Loading branch information
zpuller committed Aug 22, 2024
1 parent 795face commit 19fa1c8
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,24 +25,30 @@ object PrioritySemaphore {
}

class PrioritySemaphore[T](val maxPermits: Int)(implicit ordering: Ordering[T]) {
// This lock is used to generate condition variables, which affords us the flexibility to notify
// specific threads at a time. If we use the regular synchronized pattern, we have to either
// notify randomly, or if we try creating condition variables not tied to a shared lock, they
// won't work together properly, and we see things like deadlocks.
private val lock = new ReentrantLock()
private var occupiedSlots: Int = 0

private case class ThreadInfo(priority: T, condition: Condition)

// We expect a relatively small number of threads to be contending for this lock at any given
// time, therefore we are not concerned with the insertion/removal time complexity.
private val waitingQueue: PriorityQueue[ThreadInfo] = PriorityQueue()(Ordering.by(_.priority))

def this()(implicit ordering: Ordering[T]) = this(PrioritySemaphore.DEFAULT_MAX_PERMITS)(ordering)

def tryAcquire(numPermits: Int): Boolean = {
lock.lock()
try {
if (canAcquire(numPermits)) {
commitAcquire(numPermits)
true
} else {
false
}
if (canAcquire(numPermits)) {
commitAcquire(numPermits)
true
} else {
false
}
} finally {
lock.unlock()
}
Expand Down Expand Up @@ -74,8 +80,7 @@ class PrioritySemaphore[T](val maxPermits: Int)(implicit ordering: Ordering[T])
val nextThread = waitingQueue.dequeue()
nextThread.condition.signal()
}
}
finally {
} finally {
lock.unlock()
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2019-2024, NVIDIA CORPORATION.
* Copyright (c) 2024, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down

0 comments on commit 19fa1c8

Please sign in to comment.