require 'thread' require 'evil' Async = Class.new(KernellessObject) do def init(&blk) @th = Thread.new(&blk) @th.abort_on_exception = true Kernel.at_exit{@th.join} end def method_missing(meth,*args, &blk) __getobj__.__send__(meth,*args, &blk) end def __getobj__ @obj ||= @th.value end # control/status messages def awake @th.wakeup self end def await @th.join end def aready? ! @th.alive? end def aresult_to(obj,meth) thr = Async.new thr.init {obj.send(meth,__getobj__)} thr end end class Object def async(msg,*args,&blk) @async_queue ||= Queue.new fut = Async.new fut.init {Thread.stop;self.send(msg,*args,&blk)} @async_queue << fut @async_thread ||= Thread.new do loop{thr = @async_queue.pop.awake.await;Thread.pass} end fut end end __END__