如何与Ruby进行交互

首先,有一个主线程(在我的情况下是t2),开始和结束所有其他线程(t1)是标准的吗?

require 'curses'
include Curses

init_screen

def counter(window_name, positionx, positiony, times_factor, sleep_factor)
  window_name = Window.new(10,10,positionx,positiony)
  window_name.box('|', '-')
  window_name.setpos(2, 3)
  window_name.addstr(window_name.inspect)
  times_factor.times do |i|
    window_name.setpos(1, 1)
    window_name.addstr(i.to_s)
    window_name.refresh
    sleep sleep_factor  
  end
end
def thread1
  counter("One",10,10,50,0.01)
  counter("Two",20,20,200,0.01)
  counter("Three",30,30,3,1.0)
end
def thread2
  t1 = Thread.new{thread1()}
  x = 4
  chars = ["   ","*  ","** ","***","***","** ","*  ","   "]
  four = Window.new(20,20,10,100)
  four.box('|', '-')
  four.setpos(1, 1)
  i = 3
  while t1.alive?
    four.setpos(1, 1)
    four.addstr chars[0]   
    four.addstr i.to_s
    four.refresh
    sleep 0.1  
    chars.push chars.shift
  end
  t1.join
end

t2 = Thread.new{thread2()}
t2.join

其次,如何更改while t1.alive?循环,以便不是简单地在t1的操作期间显示星形动画,我可以提供关于t1线程内实际发生的事情的反馈?例如.,

counter1 has now finished
counter2 has now finished
counter3 has now finished

要做到这一点,每个计数器方法实际上必须在t1内的自己的线程中吗?在t1.alive期间?循环,我应该有一个案例循环,不断测试哪个循环当前存活?

这种方法意味着整个程序立即发生,而不是遵循其编写的顺序.这是更大的程序实际工作的吗?这是我应该如何提供反馈?只告诉用户某个线程何时加入?

最佳答案 thread1呼叫计数器串行;所以他们一个接一个地被饶恕了.

以下是修改后的代码.

def thread1(count)
  lock = Mutex.new
  dec_count = proc { lock.synchronize { count[0] -= 1 } }
  threads = []
  threads << Thread.new { counter("One",10,10,50,0.01); dec_count.call }
  threads << Thread.new { counter("Two",20,20,200,0.01); dec_count.call }
  threads << Thread.new { counter("Three",30,30,3,1.0); dec_count.call }
  threads.each(&:join)
end

def thread2
  active_count = [3]
  t1 = Thread.new{thread1(active_count)}
  chars = ["   ","*  ","** ","***","***","** ","*  ","   "]
  four = Window.new(3,20,10,30)
  four.box('|', '-')
  four.setpos(1, 1)
  while t1.alive?
    four.setpos(1, 1)
    four.addstr chars[0]
    four.addstr active_count[0].to_s
    four.refresh
    sleep 0.1
    chars.push chars.shift
  end
  t1.join
end

init_screen
thread2

UPDATE

在原始代码中,window_name被覆盖.在下面,我替换了参数的名称以防止这种情况.

def counter(thread_name, positiony, positionx, times_factor, sleep_factor)
  window_name = Window.new(10, 10, positiony, positionx)
  window_name.box('|', '-')
  window_name.setpos(2, 3)
  window_name.addstr(thread_name)
  times_factor.times do |i|
    window_name.setpos(1, 1)
    window_name.addstr(i.to_s)
    window_name.refresh
    sleep sleep_factor
  end
end
点赞