Ruby,简单的“线程”示例,用于更新控制台应用程序的进度

时间:2011-06-30 16:44:18

标签: ruby multithreading ruby-1.9.2

我正在尝试实现一个简单的控制台应用程序,它将执行许多长进程。在这些过程中,我想更新进度 我无法找到一个如何在任何地方做到这一点的简单示例! 就Ruby知识而言,我仍然“年轻”,而我似乎总能找到关于Thread vs Fibers vs Green Threads等的辩论。

如果有帮助,我正在使用Ruby 1.9.2。

2 个答案:

答案 0 :(得分:2)

th = Thread.new do # Here we start a new thread
  Thread.current['counter']=0
  11.times do |i| # This loops and increases i each time
    Thread.current['counter']=i
    sleep 1
  end
  return nil
end

while th['counter'].to_i < 10  do
# th is the long running thread and we can access the same variable as from inside the thread here
# keep in mind that this is not a safe way of accessing thread variables, for reading status information
# this works fine though. Read about Mutex to get a better understanding.
  puts "Counter is #{th['counter']}" 
  sleep 0.5
end

puts "Long running process finished!"

答案 1 :(得分:2)

变化稍小,您无需阅读互斥锁。

require "thread"

q = Queue.new

Thread.new do # Here we start a new thread
  11.times do |i| # This loops and increases i each time
    q.push(i)
    sleep 1
  end
end

while (i = q.pop) < 10  do
  puts "Counter is #{i}" 
end

puts "Long running process finished!"