Ruby,简单的 "threading"示例,用于更新控制台应用程序中的进度

标签 ruby multithreading ruby-1.9.2

我正在尝试实现一个简单的控制台应用程序,该应用程序将执行许多长流程。在这些过程中我想更新进度。
我无法在任何地方找到如何执行此操作的简单示例!
就 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/

相关文章:

ruby - ruby 1.9.2 和 ruby​​ 2.0 之间的主要/次要区别是什么?

ruby-on-rails-3 - "uninitialized constant Encoding"使用 rvm、ruby 1.9.2、 bundler 和乘客

regex - 允许 A-Za-z0-9 的 Ruby 正则表达式

ruby - 从数组中选择唯一的随机数

ruby-on-rails - 在 Heroku 上的 Sinatra 应用程序中, session 未跨 Dynos 共享

Java多线程-将参数传递给单个实例

Ruby Matrix set_element 私有(private)?

ruby - 如何从 Ruby 字符串中解析复杂的货币值

c - 在线程创建时将一个简单整数传递给线程的启动函数

java - 与并发共享变量