Skip to content

Commit 672f1d9

Browse files
Improved implementation.
1 parent d4af748 commit 672f1d9

File tree

2 files changed

+5
-12
lines changed

2 files changed

+5
-12
lines changed

lib/async/priority_queue.rb

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ def initialize(parent: nil)
5454
@parent = parent
5555
@waiting = IO::Event::PriorityHeap.new
5656
@sequence = 0
57+
5758
@mutex = Mutex.new
5859
end
5960

@@ -158,16 +159,10 @@ def dequeue(priority: 0)
158159
return nil
159160
end
160161

161-
# Fast path: if items available and no waiters, return immediately:
162-
if !@items.empty? && @waiting.size == 0
163-
return @items.shift
164-
end
165-
166-
# If items available but there are waiters, check if we have higher priority:
167-
if !@items.empty? && @waiting.size > 0
168-
# Peek at highest priority waiter:
169-
if @waiting.peek && priority > @waiting.peek.priority
170-
# We have higher priority, take the item immediately:
162+
# Fast path: if items available and either no waiters or we have higher priority:
163+
unless @items.empty?
164+
head = @waiting.peek
165+
if head.nil? or priority > head.priority
171166
return @items.shift
172167
end
173168
end

test/async/priority_queue.rb

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -252,8 +252,6 @@
252252

253253
low_task.wait
254254
end
255-
256-
257255
end
258256

259257
with "#waiting" do

0 commit comments

Comments
 (0)