2012-09-30 22 views
3

的示例代码是从here请解释背后的逻辑这个红宝石纤维例如

def http_get(url) 
    f = Fiber.current 
    http = EventMachine::HttpRequest.new(url).get 

    # resume fiber once http call is done 
    http.callback { f.resume(http) } 
    http.errback { f.resume(http) } 

    return Fiber.yield 
end 

EventMachine.run do 
    Fiber.new{ 
    page = http_get('http://www.google.com/') 
    puts "Fetched page: #{page.response_header.status}" 

    if page 
     page = http_get('http://www.google.com/search?q=eventmachine') 
     puts "Fetched page 2: #{page.response_header.status}" 
    end 
    }.resume 
end 

所以,在EM运行块的背景下,笔者的创建纤维与resume立即运行它。但是,我不明白为什么逻辑结构是这样构成的。我的意思是,它采用当前的光纤(在这种情况下应该是在EM运行模块中创建的光纤),它会启动一个可能失败或成功的http请求,并恢复当前的光纤。之后它只在光纤上拨打yield。自从他打电话以来究竟会发生什么情况?有人可以解释为什么http_get是这样写的吗?创建

回答

2
  1. 纤维,并引发EventMachine的
  2. 的目标是(一)抓取网页和(b)在它的工作
  3. 光纤应该暂停,直到页面被取出,这是的http_get
  4. http = EventMachine::HttpRequest.new(url).get作用不会触发任何东西:一旦EventMachine的已完成任务获得的页面EventMachine的需要得到缰绳回来,这就是Fiber.yield
  5. 的作用,它触发回调,并恢复被停止光纤在puts ...

更清晰?

+0

Fiber为什么要暂停?此外,代码停止在'puts“提取页面:#{page.response_header.status}”''直到光纤有机会运行并完成? – Geo

+1

传递给EventMachine – apneadiving

+0

谢谢,现在很明显。既然你有一些EM的经验,你可以快速浏览http://stackoverflow.com/questions/12663944/how-can-i-load-all-the-objects-inside-a-table-and-keep - 事件机器响应?也许你可以发现我做错了什么? – Geo