开发者

Ruby, simple "threading" example to update progress in console app

开发者 https://www.devze.com 2023-03-16 07:21 出处:网络
I am trying to implement a simple console app that will do lots of long processes.开发者_高级运维During these processes I want to update progress.

I am trying to implement a simple console app that will do lots of long processes.开发者_高级运维 During these processes I want to update progress.

I cannot find a SIMPLE example of how to do this anywhere!

I am still "young" in terms of Ruby knowledge and all I can seem to find are debates about Thread vs Fibers vs Green Threads, etc.

I'm using Ruby 1.9.2 if that helps.


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!"


Slightly smaller variation, and you don't need to read about 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!"
0

精彩评论

暂无评论...
验证码 换一张
取 消