Last active
January 23, 2020 13:18
-
-
Save halida/f3dbb7b9a75ceb06265a5c373a9877c7 to your computer and use it in GitHub Desktop.
work fiber
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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