Trt*_*Trt 2 ruby multithreading
我试图用Ruby尽可能快地处理1000帧.所以我目前开始1000个线程(每帧一个).结果很糟糕.它使用大量内存而且速度很慢.我的CPU是这个http://ark.intel.com/products/67355/ 它说它支持4个线程.(我猜每个CPU 2个?).因此,如果我一次启动4个Ruby线程,等到它们完成,然后再启动4个等等,它将需要250'步骤来完成处理权,而不是1000?
编辑:我的代码现在:
beginning_time = Time.now
limit=1
for frame_index in 1..limit
greyscale_frames_threads << Thread.new(frame_index) { |frame_number|
puts "Loading Image #{frame_number}"
img_processor.load_image(frames_dir+"/frame_%04d.png"%+frame_number)
img_processor.greyscale_image
img_processor.save_image_in_dir(output_dir,"frame_%04d"%+frame_number)
puts "Greyscaled Image #{frame_number}"
}
end
puts "Joining Threads"
greyscale_frames_threads.each { |thread| thread.join } #this blocks the main thread
end_time = Time.now
puts "Time elapsed #{(end_time - beginning_time)*1000} milliseconds"
Run Code Online (Sandbox Code Playgroud)
现在,对于limit = 1,这就是我得到的:
时间流逝23504.805999999997毫秒
现在,对于limit = 2,这就是我得到的:
时间流逝53465.676毫秒
对于limit = 2,我期待23504.805999999997毫秒.
这意味着我的代码失败了.线程在这里没有任何意义.为什么?有人可以向我解释一下吗?
小智 5
例如,您可以使用此类创建线程池并安排工作:
class Pool
def initialize(size)
@size = size
@jobs = Queue.new
@pool = Array.new(@size) do |i|
Thread.new do
Thread.current[:id] = i
catch(:exit) do
loop do
job, args = @jobs.pop
job.call(*args)
end
end
end
end
end
def schedule(*args, &block)
@jobs << [block, args]
end
def shutdown
@size.times do
schedule { throw :exit }
end
@pool.map(&:join)
end
end
Run Code Online (Sandbox Code Playgroud)
然后你可以pool = Pool.new(32)在那个日程表之后做这样的事情:
pool.schedule do
# do your stuff
end
Run Code Online (Sandbox Code Playgroud)
这意味着(在这个例子中)最多会有32个线程,每个线程都弹出一些你安排的工作.
| 归档时间: |
|
| 查看次数: |
1694 次 |
| 最近记录: |