Created
November 19, 2012 20:58
-
-
Save havenwood/4113840 to your computer and use it in GitHub Desktop.
Futures
This file contains 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
class Future | |
def initialize &future | |
@thread = Thread.new { @value = future.call } | |
end | |
def ready? | |
!!@value | |
end | |
def value | |
@thread.value | |
end | |
end | |
# See http://tx.pignata.com/2012/11/concurrency-patterns-in-ruby-futures.html | |
future = Future.new do | |
sleep 1 | |
puts 'Cooking...' | |
sleep 5 | |
puts '5 more seconds in the oven...' | |
sleep 5 | |
puts 'Ready.' | |
%w[Cookies! Cake. Pie! Brownies!].sample | |
end | |
#=> #<Future:0x007fe1fc76b840 @thread=%<2ac22334Thread:0x007fe1fc76b778 sleep>> | |
future.ready? | |
#=> false | |
sleep 6 | |
#=> 6 | |
# Cooking... | |
# 5 more seconds in the oven... | |
future.ready? | |
#=> false | |
sleep 5 | |
#=> 5 | |
# Ready. | |
future.ready? | |
#=> true | |
future.value | |
#=> "Cookies!" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment