Ruby 为什么我的eventmachine客户端代码没有';你不能异步工作吗? def索引 p“索引,#{Fiber.current.object_id}”#{'keyname'=>'value'} http.errback{p“Uh-oh,#{Fiber.current.object_-id};EM.stop}

Ruby 为什么我的eventmachine客户端代码没有';你不能异步工作吗? def索引 p“索引,#{Fiber.current.object_id}”#{'keyname'=>'value'} http.errback{p“Uh-oh,#{Fiber.current.object_-id};EM.stop},ruby,multithreading,asynchronous,eventmachine,fiber,Ruby,Multithreading,Asynchronous,Eventmachine,Fiber,光纤是实现轻量化协作的基本元件 Ruby中的并发性。基本上,它们是一种创建代码的方法 可以暂停和恢复的块,很像线程。主要 不同之处在于,它们从不被抢占,而且调度 必须由程序员而不是虚拟机完成 您在代码中的什么位置安排光纤,例如调用Fiber.yield或my_Fiber.resume 当前()→ 纤维 返回当前光纤。 在使用此方法之前,您需要“光纤”。如果你不是 在光纤的上下文中运行此方法将返回根 纤维 您在代码中的何处创建了其他光纤,例如Fiber.new do 这段代码甚至是异步执行的吗 如

光纤是实现轻量化协作的基本元件 Ruby中的并发性。基本上,它们是一种创建代码的方法 可以暂停和恢复的块,很像线程。主要 不同之处在于,它们从不被抢占,而且调度 必须由程序员而不是虚拟机完成

您在代码中的什么位置安排光纤,例如调用Fiber.yield或my_Fiber.resume

当前()→ 纤维
返回当前光纤。 在使用此方法之前,您需要“光纤”。如果你不是 在光纤的上下文中运行此方法将返回根 纤维

您在代码中的何处创建了其他光纤,例如Fiber.new do

这段代码甚至是异步执行的吗


如图所示,
em http
默认情况下不使用光纤。但是,该链接列出了一个示例,说明了如果您有这种倾向,可以如何使用光纤。

+1,我认为操作光纤的代码位于EventMachine和em http请求库中。你的答案是否定的,但还不清楚它是如何工作的
errback
已修复。
我认为代码运行光纤在EventMachine中
否。请仔细查看代码,然后查看输出中的对象id。您应该使用em Synchronous查看光纤:)
def index
  p "INDEX, #{Fiber.current.object_id}" # <- #1
  EventMachine.run {
    http = EventMachine::HttpRequest.new('http://google.com/').get :query => {'keyname' => 'value'}

    http.errback { p "Uh oh, #{Fiber.current.object_id}"; EM.stop } # <- #2
    http.callback {
      p "#{http.response_header.status}, #{Fiber.current.object_id}" # <- #3
      p "#{http.response_header}"
      p "#{http.response}"

      EventMachine.stop
    }
  }

  render text: 'test1'
end
require 'em-http-request'
require 'fiber'

puts Fiber.current.object_id

def index
  p "INDEX, #{Fiber.current.object_id}" # <- #1
  EventMachine.run {
    http = EventMachine::HttpRequest.new('http://google.com/').get :query => {'keyname' => 'value'}

    http.errback { p "#{Uh oh}, #{Fiber.current.object_id}"; EM.stop } # <- #2
    http.callback {
      p "#{http.response_header.status}, #{Fiber.current.object_id}" # <- #3
      p "#{http.response_header}"
      p "#{http.response}"

      EventMachine.stop
    }
  }

  #render text: 'test1'
end

index()

--output:--
2157346420
"INDEX, 2157346420"
"301, 2157346420"
"{\"LOCATION\"=>\"http://www.google.com/?keyname=value\", \"CONTENT_TYPE\"=>\"text/html; charset=UTF-8\", \"DATE\"=>\"Mon, 22 Jul 2013 08:44:35 GMT\", \"EXPIRES\"=>\"Wed, 21 Aug 2013 08:44:35 GMT\", \"CACHE_CONTROL\"=>\"public, max-age=2592000\", \"SERVER\"=>\"gws\", \"CONTENT_LENGTH\"=>\"233\", \"X_XSS_PROTECTION\"=>\"1; mode=block\", \"X_FRAME_OPTIONS\"=>\"SAMEORIGIN\", \"CONNECTION\"=>\"close\"}"
"<HTML><HEAD><meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\">\n<TITLE>301 Moved</TITLE></HEAD><BODY>\n<H1>301 Moved</H1>\nThe document has moved\n<A HREF=\"http://www.google.com/?keyname=value\">here</A>.\r\n</BODY></HTML>\r\n"
http.errback { p "#{Uh oh}"  ...