b r a y d e n . o r g / Software

/ WebHome / LanguagePages / RubyLanguage / RubyProgrammingExamples / RubyCoroutines

This Web


WebHome  
Topic List  
Web Statistics 

All Webs


Books
Main
Random
Software
TWiki  

brayden.org


Home
Monthly Digest
Today's Links
Resumé
Reading List
Books RSS
Random RSS
Software RSS

Other


Dale's Blog

currently-reading
TextDrive

A cool way of doing coroutines in Ruby

From http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-list/34953 (Tanaka Akira) -

#--- coroutine.rb ---
require 'thread'

class Thread
  def queue
    @queue = SizedQueue.new(1) unless defined? @queue
    @queue
  end

  def resume(val=nil)
    self.queue.enq val
    Thread.current.queue.deq
  end
end

class Coroutine < Thread
  def initialize(&block)
    caller = Thread.current
    super() {
      caller.resume block.call(self.queue.deq)
    }
  end
end

if $0 == __FILE__
  main = Thread.current
  c = Coroutine.new {|a|
    p a
    p 2
    p main.resume(2.5)
    p 4
    p main.resume(4.5)
    p 6
    p main.resume(6.5)
  }
  p 1
  p c.resume(1.5)
  p 3
  p c.resume(3.5)
  p 5
  p c.resume(5.5)
end

-- DaleBrayden - 05 May 2003

 
 
Current Rev: r1.1 - 05 May 2003 - 21:43 GMT - DaleBrayden, Revision History:Diffs | r1.1
© 2003-2011 by the contributing authors.