我正在尝试实现一个简单的控制台应用程序,该应用程序将执行许多长流程。在这些过程中我想更新进度。
我无法在任何地方找到如何执行此操作的简单示例!
就 Ruby 知识而言,我仍然“年轻”,我似乎能找到的只是关于线程、纤维、绿色线程等的争论。
如果有帮助的话,我正在使用 Ruby 1.9.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!"
关于Ruby,简单的 "threading"示例,用于更新控制台应用程序中的进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6538179/