Modified: MacRuby/trunk/sample-macruby/Scripts/futures.rb (3146 => 3147)
--- MacRuby/trunk/sample-macruby/Scripts/futures.rb 2009-12-22 19:43:19 UTC (rev 3146)
+++ MacRuby/trunk/sample-macruby/Scripts/futures.rb 2009-12-22 19:43:23 UTC (rev 3147)
@@ -1,19 +1,31 @@
+#!/usr/local/bin/macruby
+
+# An implementation of futures (delayed computations) on top of GCD.
+# Original implementation written by Patrick Thomson.
+# Improvements made by Ben Stiglitz.
+
include Dispatch
-
+
class Future
def initialize(&block)
- @@queue_count ||= 0
- Thread.current[:futures_queue] ||= Queue.new("org.macruby.futures-#{Thread.current.object_id}")
+ # Each thread gets its own FIFO queue upon which we will dispatch
+ # the delayed computation passed in the &block variable.
+ Thread.current[:futures] ||= Queue.new("org.macruby.futures-#{Thread.current.object_id}")
+ # Groups are just simple layers on top of semaphores.
@group = Group.new
- Thread.current[:futures_queue].async(@group) { @value = block[] }
+ # Asynchronously dispatch the future to the thread-local queue.
+ Thread.current[:futures].async(@group) { @value = block[] }
end
def value
+ # Wait fo the computation to finish. If it has already finished, then
+ # just return the value in question.
@group.wait
@value
end
end
-
+
+
f = Future.new do
sleep 2.5
'some value'