【问题标题】:Ruby, simple "threading" example to update progress in console appRuby,用于更新控制台应用程序进度的简单“线程”示例
【发布时间】:2011-06-30 16:44:17
【问题描述】:

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

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

【问题讨论】:

    标签: ruby multithreading ruby-1.9.2


    【解决方案1】:
    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!"
    

    【讨论】:

      【解决方案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!"
      

      【讨论】:

        猜你喜欢
        • 2013-04-09
        • 1970-01-01
        • 1970-01-01
        • 2012-06-23
        • 1970-01-01
        • 2023-04-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多