Skip to content

Instantly share code, notes, and snippets.

@halida
Last active January 23, 2020 13:18
Show Gist options
  • Save halida/f3dbb7b9a75ceb06265a5c373a9877c7 to your computer and use it in GitHub Desktop.
Save halida/f3dbb7b9a75ceb06265a5c373a9877c7 to your computer and use it in GitHub Desktop.
work fiber
def example
# original code
def work(item)
check?(item)
result = http_post("server/calculate", item.id)
item.update_attributes(result: result)
end
items.map{|item| work(item)}
# support async now
def work(item, opt={})
check?(item)
if opt[:async]
request = async_http_post("server/calculate", item.id)
Fiber.yield
while true
next unless request.done?
result = request.result
end
else
result = http_post("server/calculate", item.id)
end
item.update_attributes(result: result)
end
# run method
fibers = (1..3).map do |i|
Fiber.new do
Fiber.yield
while items.present?
item = items.pop
work(item, async: true)
end
end
end
while not items.empty?
fibers.sample.resume
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment