如何从控制台控制多线程

时间:2012-02-18 22:07:22

标签: ruby

学习使用Ruby Threads在不同操作系统平台之间传输代码。

问题是控制台被冻结,直到non_join1完成,这也阻止了non_join2的启动。 non_join1等待join命令,直到线程完成。

该软件需要独立运行多个例程。主程序是一个独立的程序,可以实时运行收集数据。收集的数据将写入文件。使用Threads的不同程序并行处理数据。启动/停止和状态由主控制台控制。

启动分析数据文件并从线程获取状态所需的单独程序的最佳ruby方法是什么?

感谢, PB

# This is the console that starts up the multiple threads.
#!/usr/bin/ruby

loop do
puts " input a command"
command = gets.chop!
control = case command
    when "1" : "1"
    when "2" : "2"
    end
if control == "1" then 
puts `date`+ "routine 1"
puts `./non_join1.rb`
puts `date` 
end

if control == "2" then 
puts `date` + "routine 2"
`./non_join2.rb`    
end

end


#!/usr/bin/ruby
# Example of worker program 1 used to process data files
#file non_join1.rb
x = Thread.new { sleep 0.1; print "xxxxxxxxx"; print "yyyyyyyyyyy"; print "zzzzzzzzzz" }  
a = Thread.new { print "aaaaaaaaa"; print "bbbbbbbbbb"; sleep 0.1; print "cccccccc" } 
puts " "
(1..10).each {|i| puts i.to_s+" done #{i}"}
x.join
a.join
sleep(30)

#!/usr/bin/ruby
# Example of worker program 2 used to  process data files
#file non_join2.rb
x = Thread.new { sleep 0.1; print "xxxxxxxxx"; print "yyyyyyyyyyy"; print "zzzzzzzzzz" }  
a = Thread.new { print "aaaaaaaaa"; print "bbbbbbbbbb"; sleep 0.1; print "cccccccc" } 
x.join
a.join



$ ./call_ruby.rb 
 input a command
 1
 Sat Feb 18 10:36:43 PST 2012
 routine 1
 aaaaaaaaabbbbbbbbbb 
 1 done 1
 2 done 2
 3 done 3
 4 done 4
 5 done 5
 6 done 6
 7 done 7
 8 done 8
 9 done 9
 10 done 10
 xxxxxxxxxyyyyyyyyyyyzzzzzzzzzzcccccccc
 Sat Feb 18 10:37:13 PST 2012
 input a command

1 个答案:

答案 0 :(得分:1)

使用例如此函数,而不是执行``尝试此分叉(创建新进程):

class Execute
  def self.run(command)
    pid = fork do
      Kernel.exec(command)
    end
    return pid
  end  
end

您的代码看起来像

loop do
  puts " input a command"
  command = gets.chop!
  control = case command
    when "1" : "1"
    when "2" : "2"
  end
  if control == "1" then 
    puts `date`+ "routine 1"
    Execute.run("./non_join1.rb")
    puts `date` 
  end

  if control == "2" then 
    puts `date` + "routine 2"
    Execute.run("./non_join2.rb")
  end

end