Skip to content

Instantly share code, notes, and snippets.

@Telmo
Forked from wycats/0_app.rb
Created April 22, 2012 19:15
Show Gist options
  • Save Telmo/2466262 to your computer and use it in GitHub Desktop.
Save Telmo/2466262 to your computer and use it in GitHub Desktop.
Example of using a simple future library for parallel HTTP requests
require "thread"
class Future
attr_reader :exception, :cancelled
def initialize(&block)
@thread = Thread.new(&block)
@thread.abort_on_exception = false
@exception = nil
@cancelled = false
end
def running?
@thread.alive?
end
def cancelled?
@cancelled
end
def done?
!@thread.alive?
end
def cancel
@cancelled = true
@thread.kill
end
def result(limit=nil)
value(limit)
rescue Exception => e
@exception = e
nil
end
def exception(limit=nil)
result(limit)
@exception
end
private
def value(limit)
if @thread.join(limit)
@thread.value
else
nil
end
end
end
q = Queue.new
require "uri"
require "net/http"
futures = {}
["http://www.google.com", "http://www.heroku.com", "http://www.github.com"].each do |url|
futures[url] = Future.new { Net::HTTP.get(URI(url)) }
end
futures["http://www.github.com"].cancel
puts "heroku.com:"
p futures["http://www.heroku.com"].cancelled?
puts futures["http://www.heroku.com"].result
puts futures["http://www.heroku.com"].exception
puts
puts "google.com:"
p futures["http://www.google.com"].cancelled?
puts futures["http://www.google.com"].result
puts futures["http://www.google.com"].exception
puts "github.com:"
p futures["http://www.github.com"].cancelled?
puts futures["http://www.github.com"].result
puts futures["http://www.github.com"].exception
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment