Created
April 19, 2012 15:33
-
-
Save georgi/2421760 to your computer and use it in GitHub Desktop.
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
def self.defer op = nil, callback = nil, &blk | |
# OBSERVE that #next_tick hacks into this mechanism, so don't make any changes here | |
# without syncing there. | |
# | |
# Running with $VERBOSE set to true gives a warning unless all ivars are defined when | |
# they appear in rvalues. But we DON'T ever want to initialize @threadqueue unless we | |
# need it, because the Ruby threads are so heavyweight. We end up with this bizarre | |
# way of initializing @threadqueue because EventMachine is a Module, not a Class, and | |
# has no constructor. | |
unless @threadpool | |
require 'thread' | |
@threadpool = [] | |
@threadqueue = ::Queue.new | |
@resultqueue = ::Queue.new | |
spawn_threadpool | |
end | |
@threadqueue << [op||blk,callback] | |
end | |
# @private | |
def self.spawn_threadpool | |
until @threadpool.size == @threadpool_size.to_i | |
thread = Thread.new do | |
Thread.current.abort_on_exception = true | |
while true | |
op, cback = *@threadqueue.pop | |
result = op.call | |
@resultqueue << [result, cback] | |
EventMachine.signal_loopbreak | |
end | |
end | |
@threadpool << thread | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment