Ruby线程:复制期间的进度条

时间:2013-12-23 20:15:01

标签: ruby multithreading

我对Ruby Threads很新,所以有人能让我知道我在这里做错了吗?

require 'fileutils'
require 'zip'
require 'rubygems'
require 'progressbar'

oraclePath = "\\\\server\\Oracle Client\\Oracle_11gR2\\win64_11gR2_client.zip"

begin
tmpDir = Dir.mktmpdir("ora-")

progress = Thread.new(){
  Thread.current[:name] = "FileProgress"

  sourceFileSize = File.size("#{oraclePath}")
  batch_bytes = ( in_size / 100 ).ceil
  total       = 0
  p_bar       = ProgressBar.new('Copying', 100)

  buffer      = "#{oraclePath}".sysread(batch_bytes)
  while total < sourceFileSize do
    "#{tmpDir}".syswrite(buffer)
    p_bar.inc
    total += batch_bytes
    if (sourceFileSize - total) < batch_bytes
      batch_bytes = (sourceFileSize - total)
    end
    buffer = "#{oraclePath}".sysread(batch_bytes)
  end
  p_bar.finish
}

progress.run

puts "#{tmpDir}"
FileUtils.cp_r("#{oraclePath}","#{tmpDir}")
Zip::File.open("#{tmpDir}/win64_11gR2_client.zip") do |zipfile|
  `unzip -j #{zipfile} -d #{dir}`
  #zipfile.each do |file|
  #zipfile.extract(file, "#{tmpDir}")
  #end
end

ensure
  # remove the temp directories
  FileUtils.remove_entry_secure tmpDir
end

复制有效,但线程没有 - 我甚至无法进入它;它只是完全跳过它。

1 个答案:

答案 0 :(得分:0)

Ruby Thread将在使用Thread.new实例化的那一刻开始运行,因此在您的示例中,副本立即开始,并且不需要行progress.run

如果线程本身已停止(即在等待进一步指示时自行调用run),您只需要调用stop

作为参考,您可以在此处找到更多信息:http://ruby-doc.org/core-2.0.0/Thread.html