Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 添加要在队列中提取的图像,然后抓取它们_Ruby_Multithreading - Fatal编程技术网

Ruby 添加要在队列中提取的图像,然后抓取它们

Ruby 添加要在队列中提取的图像,然后抓取它们,ruby,multithreading,Ruby,Multithreading,我对ruby mutli线程相当陌生,对如何开始感到困惑。我目前正在构建一个应用程序,它需要获取大量图像,所以我想在另一个线程中完成它。我想让程序按照下面的代码执行 问题:我在这里看到的问题是,bar_方法将更快地完成抓取,并且线程将结束,因此事情将不断添加到队列中,但不会被处理。是否有任何可能的同步方法可以提醒bar_方法线程已将新项目添加到队列中,如果bar_方法确实提前完成,它应该进入睡眠状态并等待将新项目添加到队列中 def foo_method queue created - c

我对ruby mutli线程相当陌生,对如何开始感到困惑。我目前正在构建一个应用程序,它需要获取大量图像,所以我想在另一个线程中完成它。我想让程序按照下面的代码执行

问题:我在这里看到的问题是,bar_方法将更快地完成抓取,并且线程将结束,因此事情将不断添加到队列中,但不会被处理。是否有任何可能的同步方法可以提醒bar_方法线程已将新项目添加到队列中,如果bar_方法确实提前完成,它应该进入睡眠状态并等待将新项目添加到队列中

def foo_method 
  queue created - consists of url to fetch and a callback method
  synch = Mutex.new
  Thread.new do
    bar_method synch, queue 
  end
  100000.times do
    synch.synchronize do
      queue << {url => img_url, method_callback => the_callback}
    end
  end
end
def bar_method synch_obj, queue
  synch_obj.synchronize do
    while queue isn't empty
        pop the queue. fetch image and call the callback
    end   
  end
end 
def foo_方法
队列已创建-由要获取的url和回调方法组成
synch=Mutex.new
新做的
bar_方法同步,队列
结束
10万倍
同步
队列img\u url,方法\u callback=>the\u callback}
结束
结束
结束
def bar_方法同步对象,队列
同步对象
当队列不为空时
弹出队列。获取图像并调用回调函数
结束
结束
结束

如果您需要从internet检索文件,并使用并行请求,我强烈推荐

从文件中:

hydra = Typhoeus::Hydra.new
10.times.map{ hydra.queue(Typhoeus::Request.new("www.example.com", followlocation: true)) }
hydra.run
# make multiple GET requests
easy_options = {:follow_location => true}
multi_options = {:pipeline => true}

Curl::Multi.get('url1','url2','url3','url4','url5', easy_options, multi_options) do|easy|
  # do something interesting with the easy response
  puts easy.last_effective_url
end
您可以在Hydra中设置并发连接数:

:max_concurrency(整数)-要创建的最大并发连接数。默认值为200

作为第二项建议,请调查。同样,从其文件中:

hydra = Typhoeus::Hydra.new
10.times.map{ hydra.queue(Typhoeus::Request.new("www.example.com", followlocation: true)) }
hydra.run
# make multiple GET requests
easy_options = {:follow_location => true}
multi_options = {:pipeline => true}

Curl::Multi.get('url1','url2','url3','url4','url5', easy_options, multi_options) do|easy|
  # do something interesting with the easy response
  puts easy.last_effective_url
end
两者都是构建在Curl之上的,所以它们的底层技术或健壮性没有真正的区别。区别在于您可以使用的命令

另一个备受关注的宝石是EventMachine。它具有允许并发请求的功能:

EventMachine.run {
  http1 = EventMachine::HttpRequest.new('http://google.com/').get
  http2 = EventMachine::HttpRequest.new('http://yahoo.com/').get

  http1.callback { }
  http2.callback { } 
end