[macruby-changes] [3146] MacRuby/trunk/futures.rb

source_changes at macosforge.org source_changes at macosforge.org
Tue Dec 22 11:43:20 PST 2009


Revision: 3146
          http://trac.macosforge.org/projects/ruby/changeset/3146
Author:   pthomson at apple.com
Date:     2009-12-22 11:43:19 -0800 (Tue, 22 Dec 2009)
Log Message:
-----------
Added comments and removed an unneessary variable.

Added Paths:
-----------
    MacRuby/trunk/futures.rb

Added: MacRuby/trunk/futures.rb
===================================================================
--- MacRuby/trunk/futures.rb	                        (rev 0)
+++ MacRuby/trunk/futures.rb	2009-12-22 19:43:19 UTC (rev 3146)
@@ -0,0 +1,34 @@
+#!/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)
+    # 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
+    # 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'
+end
+ 
+p f.value
\ No newline at end of file
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.macosforge.org/pipermail/macruby-changes/attachments/20091222/e0e4e167/attachment-0001.html>


More information about the macruby-changes mailing list