Skip to content

Instantly share code, notes, and snippets.

@wolverian
Forked from wycats/0_app.rb
Created April 19, 2012 10:56
Show Gist options
  • Save wolverian/2420239 to your computer and use it in GitHub Desktop.
Save wolverian/2420239 to your computer and use it in GitHub Desktop.
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?
[email protected]?
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
future = Future.new { q.pop; raise "ZOMG" }
Thread.new { sleep 1; q.push "value" }
puts "HI!"
p future.result
p future.exception
puts "BYE!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment