2011-09-20 33 views
0

請原諒我,如果這是一個愚蠢的問題;我對線程很陌生。 我運行一個線程,將完成當我改變它keeprunning狀態,像這樣:在Python中加入一個始終運行的線程

class mem_mon(threading.Thread): 
    def __init__(self): 
     threading.Thread.__init__(self) 
     self.keeprunning = True 
     self.maxmem = 0 
    def run(self): 
     while self.keeprunning: 
      self.maxmem = max(self.maxmem, ck_mem()) 
      time.sleep(10) 

但由於sleep電話,我經常要等上一段時間他們加入之前。除了創建一個更頻繁檢查keeprunning的更快的循環之外,有什麼我可以做的更快速地加入線程?例如通過覆蓋__del__join

+2

使用'threading.Event'或'threading.Condition'對象。 – wberry

+0

謝謝 - 這就是我想說的,不記得有一個單獨的課程。 – lunixbochs

回答

3

使用threading.Event作爲time.sleep()您可以中斷。

class mem_mon(threading.Thread): 
    def __init__(self): 
     threading.Thread.__init__(self) 
     self.keeprunning = True 
     self.maxmem = 0 
     self.interrupt = threading.Event() 

    def run(self): 
     # this loop will run until you call set() on the interrupt 
     while not self.interrupt.isSet(): 
      self.maxmem = max(self.maxmem, ck_mem()) 

      # this will either sleep for 10 seconds (for the timeout) 
      # or it will be interrupted by the interrupt being set 
      self.interrupt.wait(10) 

mem = mem_mon() 
mem.run() 

# later, set the interrupt to both halt the 10-second sleep and end the loop 
mem.interrupt.set() 
0

我能想到的最簡單的辦法是最醜的,以及 - 我曾經看到怎麼殺在Python任何線程,在這個配方:http://icodesnip.com/snippet/python/timeout-for-nearly-any-callable - 我從來沒有使用它,因爲需要使用鎖和隊列,但可能性在那裏。

+0

當一個互斥事件可以完成相同數量的代碼時,醜陋的解決方案並不是必需的 – lunixbochs

+0

你當然是對的,我只是認爲值得知道有這樣的解決方案。我能想到的一個例子是使用遺留代碼的時候 - 殺死一些線程比部分重寫它更容易。但正如我所說,我從來沒有使用過它,我不知道什麼時候或者如果我會。這只是一些好奇,值得了解恕我直言:) – cji

+0

您的鏈接已損壞。 – preezzzy