我无法理解为什么这段代码不起作用。 我要做的是使用光纤模拟同步代码行为。
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
光纤永远不会恢复。 你能解释我怎么能这样做?
谢谢你们
答案 0 :(得分: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
你会得到
#=> Fiber Started
#=> Resuming Fiber
#=> page fetched http://www.whatever.com