Last active
August 29, 2015 14:09
-
-
Save ksss/2af768c068f4efcf3143 to your computer and use it in GitHub Desktop.
Pure Ruby Queue sample
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env ruby | |
class PureRubyQueue | |
def initialize | |
@que = [] | |
@waiters = [] | |
end | |
def push(obj) | |
@que << obj | |
while t = @waiters.shift | |
if t.wakeup | |
break | |
end | |
end | |
self | |
end | |
def pop(non_block=false) | |
while @que.length == 0 | |
if non_block | |
raise ThreadError, "queue empty" | |
end | |
@waiters << Thread.current | |
begin | |
Thread.stop | |
ensure | |
@waiters.delete(Thread.current) | |
end | |
end | |
@que.shift | |
end | |
end | |
[Queue, PureRubyQueue].each do |klass| | |
q = klass.new | |
10.times do |i| | |
q.push i | |
end | |
threads = [] | |
3.times do | |
threads << Thread.new { | |
begin | |
while val = q.pop(true) | |
p val | |
sleep 0.1 | |
end | |
rescue ThreadError | |
puts "thread finish!" | |
end | |
} | |
end | |
threads.each(&:join) | |
puts "thread all joined" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment