Created
April 23, 2013 22:49
-
-
Save ahoward/5448091 to your computer and use it in GitHub Desktop.
portable (jruby / ruby) queue that should work in ruby 2.0, planning to use handling signals pushed via trap(sig){ ... }
This file contains 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
class Kew | |
require 'thread' | |
require 'socket' | |
def initialize | |
@pipes = UNIXSocket.pair(:STREAM, 0) | |
@mutex = Mutex.new | |
end | |
def pipe | |
unless storage[:pipe] | |
@mutex.synchronize do | |
pipe = @pipes.pop | |
raise IndexError, 'no moar pipes!' unless pipe | |
storage[:pipe] = pipe | |
end | |
else | |
storage[:pipe] | |
end | |
end | |
def storage | |
((Thread.current[:_qs] ||= {})[object_id] ||= {}) | |
end | |
def push(object) | |
buf = Marshal.dump(object) | |
pipe.puts(buf.size) | |
pipe.write(buf) | |
end | |
def pop | |
size = pipe.gets.to_i | |
buf = pipe.read(size) | |
Marshal.load(buf) | |
end | |
end | |
k = Kew.new | |
Thread.new do | |
loop do | |
p k.pop.last | |
end | |
end | |
3.times do | |
k.push [0,1,2, 42] | |
end | |
sleep | |
__END__ | |
42 | |
42 | |
42 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment