Skip to content

Instantly share code, notes, and snippets.

@hitode909

hitode909/duel.rb

Created Nov 11, 2012
Embed
What would you like to do?
並列に実行して最初に返ってきた結果を得るやつ
class Duel
def initialize(*jobs)
@lock = Mutex.new
@done = false
make_thread(jobs)
end
def join
return if @done
@threads.first.join
end
def done?
lock {
@done
}
end
def kill
lock {
_kill
}
end
def result
raise 'running' unless done?
@result
end
protected
def make_thread(jobs)
@threads = jobs.map{|job|
Thread.new {
result = job.call
kill
@result = result
}
}
end
def lock(&block)
res = nil
@lock.synchronize {
res = block.call
}
res
end
def _kill
@threads.select{ |t|
t != Thread.current
}.each{ |t|
t.kill
}
@done = true
end
end
require 'open-uri'
require 'nokogiri'
duel = Duel.new(lambda{
(Nokogiri open 'http://hitode909.hatenablog.com').at('title').content
},
lambda {
(Nokogiri open 'http://hatenablog.com').at('title').content
}
)
duel.join
puts duel.result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment