I have an array of URLs and I wan't to open each one and fetch a specific tag.
But I want to do this in parallel.
Here is the pseudocode for what I want to do:
urls = [...] tags = [] urls.each do |url| fetch_tag_asynchronously(url) do |tag| tags << tag end end wait_for_all_requests_to_finish()
If this could be done in a nice and safe way that would be awesome.
I could use thread but it doesn't look like arrays are thread safe in ruby.
You can achieve thread-safety by using a
Mutex
:It could however be counter-productive to use a new thread for every URL, so limiting the number of threads like this might be more performant:
Thanks to ruby's GIL this should be safe, based on my reading of http://merbist.com/2011/02/22/concurrency-in-ruby-explained/ and further links.
The Typhoeus/Hydra gem combination is designed to do this very easily. It's very convenient and powerful.