4

The example code is from 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

So, in the context of the EM run block, the author's creating a fiber and running it immediately with resume. But, I don't understand why the http_get logic is structured in that way. I mean, it's taking the current fiber ( which in this case should be the one created in the EM run block ), it starts a http request which may fail or succeed, and it resumes the current fiber. Afterwards it just calls yield on the fiber. What exactly will be running since he is calling yield? Can someone please explain why http_get is written the way it is?

Geo
  • 93,257
  • 117
  • 344
  • 520

1 Answers1

3
  1. Fiber is created and triggered in EventMachine
  2. the goal is (a) to fetch a page and (b) work on it
  3. the Fiber should be paused until the page is fetched, this is the role of http_get
  4. http = EventMachine::HttpRequest.new(url).get doesn't trigger anything: EventMachine needs to get the reins back, that's the role of Fiber.yield
  5. Once EventMachine has done the job getting the page, it triggers the callback and resumes the Fiber which was stopped at puts ...

Clearer?

apneadiving
  • 114,565
  • 26
  • 219
  • 213
  • Why should the Fiber be paused? Also, the code stops at `puts "Fetched page: #{page.response_header.status}"` until the fiber gets a chance to run& complete? – Geo Sep 30 '12 at 18:59
  • 1
    to pass the hand to EventMachine – apneadiving Sep 30 '12 at 19:01
  • Thank you, now it's clear. Since you have some EM experience, could you maybe have a quick look at http://stackoverflow.com/questions/12663944/how-can-i-load-all-the-objects-inside-a-table-and-keep-eventmachine-responsive ? Maybe you can spot what I'm doing wrong? – Geo Sep 30 '12 at 19:01
  • Is there a race condition? e.g. is it possible for resume to be called before yield? – ioquatix Jan 18 '14 at 12:23