Skip to content

Instantly share code, notes, and snippets.

@benolee
Forked from qerub/gist:4137421
Created April 23, 2013 04:47
Show Gist options
  • Save benolee/5440920 to your computer and use it in GitHub Desktop.
Save benolee/5440920 to your computer and use it in GitHub Desktop.
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