Created
November 11, 2012 01:00
-
-
Save hitode909/4053208 to your computer and use it in GitHub Desktop.
並列に実行して最初に返ってきた結果を得るやつ
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 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