0

我无法理解,为什么这段代码不起作用。我想做的是使用光纤模拟同步代码行为。

require 'fiber'
require 'eventmachine'

def async_request(url)
  f = Fiber.current
  Thread.new do
    sleep 0.3
    puts 'Resuming Fiber'
    f.resume('page fetched #{url}')
  end
end


def async_get(url)
  async_request url
  val = Fiber.yield
  return val
end

EM.run do 

  Fiber.new do
    puts 'Fiber Started'
    page = async_get('http://www.whatever.com')
    puts page
  end.resume

end

当我运行此代码时,输​​出为:

$ ruby fiber_poc.rb
  Fiber Started
  Resuming Fiber

光纤永远不会恢复。你能解释一下我该怎么做吗?

多谢你们

4

1 回答 1

1
require 'fiber'
require 'eventmachine'

def async_request(url)
  f = Fiber.current
  EM.add_timer(0.3) do
    puts 'Resuming Fiber'
    f.resume("page fetched #{url}")
  end
end

def async_get(url)
  async_request url
  Fiber.yield
end

EM.run do 
  Fiber.new do
    puts 'Fiber Started'
    page = async_get('http://www.whatever.com')
    puts page
    EM.stop
  end.resume
end

you will get

#=> Fiber Started
#=> Resuming Fiber
#=> page fetched http://www.whatever.com
于 2013-08-22T14:12:28.997 回答