-
-
Save wolverian/2420239 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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