Skip to content

Instantly share code, notes, and snippets.

@drernie
Created January 28, 2010 01:04
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 drernie/288328 to your computer and use it in GitHub Desktop.
Save drernie/288328 to your computer and use it in GitHub Desktop.
module Dispatch
# Wrapper around Dispatch::Group used to implement lazy Futures
class Future
# Create a future that asynchronously dispatches the block
# to a concurrent queue of the specified (optional) +priority+
def initialize(priority=nil, &block)
@group = Group.new
@value = nil
Dispatch::Queue.concurrent(priority).async(@group) { @value = block.call }
end
# Waits for the computation to finish, then returns the value
# Duck-typed to lambda.call(void)
def call()
@group.wait
@value
end
# Passes the value to the +callback+ block when it is available
# Duck-typed to group.notify
def notify(&callback)
@group.notify { callback.call(@value) }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment