2012-09-07 36 views
0

我正在使用內部具有常量循環的線程。我想檢查線程睡眠的時間。如何在紅寶石中找到睡眠線程的時間?

如何找到線程的休眠時間?

這裏是代碼

t = Thread.new{ 
    loop do 
     puts "thread " 
     threads=Thread.list 
     threads.each_with_index do |th,index|    
      th.status == "run" ? th.priority = 2 : th.priority = 0 
      if th.status == "false" || th.status == "sleep" 
       th.kill 
      end 
      print "thread #{th} : State=> #{th.status} : priority=> #{th.priority} :index=> #{index} \n "    
     end 
    end 
    } 

我想知道休眠線程的時間,這樣我可以殺正確的。由於螺紋的生活應該在某個階段被殺害

回答

2

您可以設置線程級變量來獲取信息創建定線程時:

t = Thread.new{} 
t[:created_at] = Time.now 

如果你想知道線程多長時間處於睡眠狀態,你需要每次線程進入睡眠狀態時設置該值,並在喚醒後重置。 所以你的支票看起來像

th.kill if Time.now - th[:created_at] > MAX_THREAD_LIFETIME