Skip to content

Instantly share code, notes, and snippets.

@qerub
Created November 23, 2012 21:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save qerub/4137421 to your computer and use it in GitHub Desktop.
Save qerub/4137421 to your computer and use it in GitHub Desktop.
Simple Futures in Ruby with Lambdas and Threads
def future # :block:
thread = Thread.new do
Thread.current.abort_on_exception = false
yield
end
lambda { thread.value }
end
def compose(proc) # :block:
lambda { |*args| yield proc.call(*args) }
end
# Example:
f1 = future {
(1..3).each { puts "Sleeping in #{Thread.current}..."; sleep 1 }
next 1
}
f2 = compose(f1) { |x| x + 1 }
f3 = compose(f2) { |x| x * 2 }
puts "Waiting for result in #{Thread.current}..."
puts f3.call
# Another example (parallel HTTP fetch):
require "open-uri"
urls = ["http://echo.fruktsallad.net/?foo", "http://echo.fruktsallad.net/?bar"]
responses = urls.map { |x| future { open(x).read } }.map(&:call)
results = urls.zip(responses)
# => [["http://echo.fruktsallad.net/?foo", "foo"], ["http://echo.fruktsallad.net/?bar", "bar"]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment