2012-02-18 76 views
1

學習如何在不同操作系統平臺之間使用Ruby線程實現代碼的可移植性。如何從控制檯控制多線程

問題是控制檯被凍結,直到non_join1完成這也會妨礙non_join2被啓動。 non_join1等待連接命令,直到線程完成。

該軟件需要多個例程獨立運行。主程序是一個獨立運行的實時收集數據。收集的數據被寫入文件。使用線程的不同程序並行處理數據。啓動/停止和狀態由主控制檯控制。

什麼是最好的紅寶石方法來啓動分析數據文件並獲取狀態從螺紋回所需的單獨的程序?

感謝, 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

所以,你想要的程序不等待'/ non_join1'到結束,從日返回電話?爲此你可以使用'Process.spawn'。 – Linuxios 2012-02-18 23:40:41

回答

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