Skip to content

Instantly share code, notes, and snippets.

@mltsy
Last active December 17, 2015 10:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mltsy/5595691 to your computer and use it in GitHub Desktop.
Save mltsy/5595691 to your computer and use it in GitHub Desktop.
This is an extension to the Ruby Enumerable Module that allows you to take any enumerable and run the same block of code on all of the elements simultaneously in separate threads, returning either the fastest result (and terminating all other threads), or all results once all the threads have finished. The intended use-case for the return_fastes…
module Enumerable
# A special exception used to signal that the fastest result has been found
# in execution of all_at_once
class FastestResultFound < Exception
end
# Runs the given block on all items at the same time (in separate threads).
# If return_fastest is false (default), returns an array of all results, in
# the same order as the elements
# If return_fastest is true, stops execution of the other threads as soon
# as a result is found and returns only the fastest result.
def all_at_once(return_fastest = false)
results = []
threads = []
self.each_with_index do |item, index|
threads << Thread.new do
begin
results[index] = yield item
rescue => e
# Raise any exceptions immediately to the main thread
Thread.main.raise e
end
if return_fastest
# When a result is found, raise this exception to continue
# execution of the main thread, and indicate which result was
# the fastest.
Thread.main.raise FastestResultFound, index.to_s
end
end
end
# Wait for results
threads.each(&:join)
# The results are in! Return them all
return results
rescue FastestResultFound => exception
# We have a fastest result; stop the other threads, and return it
threads.each(&:exit)
index = exception.message.to_i
results[index]
rescue => e
# We have a problem; stop the other threads and raise the exception,
# but first, modify it to include the entire stack trace.
threads.each(&:exit)
e.set_backtrace(e.backtrace + caller)
raise e
end
end
# Let's give it a spin...
fastest_result = (1..5).all_at_once(true) do |i|
sleep rand(0.9)
i
end
puts fastest_result
results = (1..5).all_at_once do |i|
sleep rand(0.9)
i
end
puts results
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment