# # $Id: future.rb,v 1.5 2003/03/18 13:23:55 fukumoto Exp $ # # future { ... } # # Object # future? # # Future # Future.new { ... } # future? # __done? # __wait__ # inspect # to_a, to_s, ==, =~, ===, method_missing # def future(*param) Future.new(param) { |args| yield *args } end class Object def future? false end end class Future def initialize(*param) @th = Thread.new(param) { |args| begin yield(*args) rescue print $! if $VERBOSE # ??? raise end } end def future? @th.alive? end def __done? not @th.alive? end def __wait__ @th.join end def inspect if @th.alive? sprintf("#", self.__id__) else @th.value.inspect end end [:to_a, :to_s, :==, :=~, :===].each do |op| eval <<-End def #{op}(*args, &block) @th.value.__send__(:#{op}, *args, &block) end End end def method_missing(name, *args, &p) @th.value.__send__ name, *args, &p end end # end of class Future module Enumerable def map_in_parallel self.map { |item| future(item) { |i| yield i } } end end if __FILE__ == $0 a = (0..9).map { |i| future { sleep 10*rand; i**2 } } end