With Ruby 3.0 the async
gem is now compatible with blocking IO in standard library functions and I wanted to understand the basic functionality but am already confused by a simple example:
require 'async'
n = 10
n.times do |i|
Async do
HTTParty.get("https://httpbin.org/delay/1.6")
end
end
This doesn't show any parallelism. Looking in the Gem's documentation about Kernel#async
says:
Run the given block of code in a task, asynchronously, creating a reactor if necessary.
But the project documentation seems to clear it up:
When invoked at the top level, will create and run a reactor, and invoke the block as an asynchronous task. Will block until the reactor finishes running.
So to make the example from above work:
require 'async'
n = 10
Async do
n.times do |i|
Async do
HTTParty.get("https://httpbin.org/delay/1.6")
end
end
end
This works, but seems confusing to the reader. How would we know as readers that the first Async do
is blocking while the others are not?
Thus the question: What is the canonical basic usage of the async
gem?
Further reading: