Created
June 6, 2017 16:06
-
-
Save fsword/38199512aee687733fc14193ec9b1071 to your computer and use it in GitHub Desktop.
fiber练习,模拟管道功能
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class PipeElement | |
attr_accessor :source | |
def initialize | |
@delegator = Fiber.new do | |
process | |
end | |
end | |
def | other | |
other.source = self | |
other | |
end | |
def process | |
while v = receive | |
handle v | |
end | |
end | |
def handle v | |
send v | |
end | |
def send v | |
puts "----------------#{self.class}: send" | |
Fiber.yield v | |
end | |
def receive | |
source.resume | |
end | |
def resume | |
puts "----------------#{self.class}: resume" | |
@delegator.resume | |
end | |
end | |
class Producer < PipeElement | |
def receive | |
gets | |
end | |
end | |
class Filter < PipeElement | |
def initialize | |
super | |
@line = 1 | |
end | |
def handle v | |
send "#{@line}: #{v}" | |
@line += 1 | |
end | |
end | |
class Stop < PipeElement | |
def receive | |
v = source.resume | |
return nil if v.chomp.include?('stop') | |
v | |
end | |
end | |
class Consumer < PipeElement | |
def handle v | |
puts v | |
end | |
end | |
x = Producer.new | |
y = Filter.new | |
z = Consumer.new | |
a = Stop.new | |
t = x | a | y | z | |
t.resume |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment