require 'net/http'
def get(url)
uri = URI(url)
response = Net::HTTP.get_response(uri)
puts response.body
end
threads = []
threads << Thread.new {
# assume that this is call to update the user
get('https://jsonplaceholder.typicode.com/todos/1')
}
threads << Thread.new {
# assume that this is call to delete something get('https://jsonplaceholder.typicode.com/posts/2')
}
threads << Thread.new {
# some more network call
get('https://jsonplaceholder.typicode.com/posts/3')
}
threads.each(&:join)
puts "All good let's exit"
1条答案
按热度按时间4uqofj5v1#
我不确定您要执行的操作,但假设其中一些是网络调用,一种方法是使用某种后台工作程序。
在任何情况下,无论您是通过工人还是Web控制器调用,都可以使用线程进行并行调用。
例如,考虑下面的代码,它创建了3个线程,并等待每个线程完成。
线程是一个有点复杂的主题,所以您可能需要研究一下。对于初学者,您可以参考类似于-https://www.rubyguides.com/2015/07/ruby-threads/的内容