Skip to content

Instantly share code, notes, and snippets.

@avalanche123
Created March 9, 2012 05:34
Show Gist options
  • Save avalanche123/2005191 to your computer and use it in GitHub Desktop.
Save avalanche123/2005191 to your computer and use it in GitHub Desktop.
Python's greenlets in Ruby using fibers, implementing example from greenlet documentation at http://greenlet.readthedocs.org/en/latest/index.html
class String
def start_with?(little_string)
!self.match(/^#{Regexp.escape(little_string)}/).nil?
end
def end_with?(little_string)
!self.match(/#{Regexp.escape(little_string)}$/).nil?
end
end
class Greenlet
require 'fiber'
current = begin
instance = allocate
instance.instance_variable_set(:@parent, instance)
instance.instance_variable_set(:@fiber, Fiber.current)
instance
end
instance_variable_set(:@current, current)
def self.new(&block)
instance = allocate
instance.instance_variable_set(:@parent, @current)
instance.instance_variable_set(:@fiber, Fiber.new(&block))
@current = instance
end
def self.current
@current
end
attr_reader :parent
def switch(*args)
@fiber.transfer(*args)
end
end
def Greenlet(&block)
Greenlet.new &block
end
def process_commands(*args)
while true
line = ''
until line.end_with?("\n")
line += read_next_char()
end
if line == "quit\n"
puts "are you sure?"
if read_next_char() != 'y'
continue
end
end
process_command(line)
end
end
def process_command(cmd)
puts cmd
end
def event_keydown(key)
@g_processor.switch(key)
end
def read_next_char()
g_self = Greenlet.current
next_char = g_self.parent.switch()
return next_char
end
@g_processor = Greenlet(&method(:process_commands))
@g_processor.switch([])
event_keydown("h")
event_keydown("e")
event_keydown("l")
event_keydown("l")
event_keydown("o")
event_keydown(" ")
event_keydown("w")
event_keydown("o")
event_keydown("r")
event_keydown("l")
event_keydown("d")
event_keydown("!")
event_keydown("\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment