Skip to content

Instantly share code, notes, and snippets.

@hitode909
Created November 11, 2012 01:00
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hitode909/4053208 to your computer and use it in GitHub Desktop.
Save hitode909/4053208 to your computer and use it in GitHub Desktop.
並列に実行して最初に返ってきた結果を得るやつ
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