Skip to content

Instantly share code, notes, and snippets.

@0xradical
Created June 19, 2014 04:36
Show Gist options
  • Save 0xradical/0fb1be723c01947af227 to your computer and use it in GitHub Desktop.
Save 0xradical/0fb1be723c01947af227 to your computer and use it in GitHub Desktop.
fibers_and_em.rb
# Trying to grasp fibers and EM!
# Using this example: http://www.slideshare.net/kbal11/ruby-19-fibers (slide 54)
# Fiber#resume(*params) => when first called, it passes all params as block params to
# Fiber.new
# In the next calls of resumes, *params is the return value of any Fiber.yield
# Fiber.yield stops execution of current fiber
# So, in the run-loop from EM, the fiber stops execution and gives up control
# to EM run-loop, because of Fiber.yield in the last line of http_get.
# The machine sits there doing nothing else (http://javieracero.com/blog/starting-with-eventmachine-i)
# When callback or errback is called, the fiber execution is resumed automatically and `http' is
# passed as param, which is the return value of Fiber.yield, which is assigned to page and then
# the execution continues up until the next http_get, where the same logic starts to apply once again.
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 do
page = http_get('http://www.google.com.br')
puts "Fetched page: #{page.response_header.status}"
page = http_get('http://www.google.com.br/search?q=eventmachine')
puts "Fetched page: #{page.response_header.status}"
end.resume
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment