2

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

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

4

2 回答 2

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!"
于 2011-06-30T17:52:31.833 回答
2

稍微小一点的变化,你不需要阅读 Mutex。

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!"
于 2011-06-30T20:37:02.850 回答