Skip to content

Instantly share code, notes, and snippets.

@JacobNinja
Created April 9, 2013 15:57
Show Gist options
  • Save JacobNinja/5346915 to your computer and use it in GitHub Desktop.
Save JacobNinja/5346915 to your computer and use it in GitHub Desktop.
urls = ['http://www.google.com', 'http://www.github.com', 'http://www.twitter.com']
concurrent_url_grabber = Enumerator.new do |y|
urls.map do |url|
Thread.new do
result = http_request(url)
# Need a mutex here for multithreaded VMs
y << result
end
end.each(&:join)
end
concurrent_url_grabbler.map(&:code) # => ['200', '200', '200']
@jstorimer
Copy link

FYI if you use each(&:value), instead of each(&:join), you don't need to worry about the mutex (and it's still thread-safe).

@rhodee
Copy link

rhodee commented Apr 23, 2013

@jstorimer I had a different take on the difference between Thread#value and Thread#join. I thought #value calls #join internally and returns a value, while #join returns the instance of the new Thread? Is that not correct? If it is I do not see how there is no need for mutex at first glance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment