Skip to content

Instantly share code, notes, and snippets.

@havenwood
Created November 19, 2012 20:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save havenwood/4113840 to your computer and use it in GitHub Desktop.
Save havenwood/4113840 to your computer and use it in GitHub Desktop.
Futures
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