2011-12-07 35 views
3

我已經延長threading.Thread有道 - 我的想法是做這樣的事情:的Python:什麼是參數傳遞給threading.Thread例如

class StateManager(threading.Thread): 
    def run(self, lock, state): 
     while True: 
      lock.acquire() 
      self.updateState(state) 
      lock.release() 
      time.sleep(60) 

我需要能夠通過參考我的「狀態」對象並最終鎖定(我對多線程相當陌生,但仍然對鎖定Python的必要性感到困惑)。什麼是正確的方法來做到這一點?

+0

這不是我很清楚你需要尋找到你的代碼是什麼?通過您的帖子的標題,在我看來,您可能會在同步隊列之後:http://docs.python.org/library/queue.html。 – dsign

回答

7

在構造函數中傳遞它們,例如,

class StateManager(threading.Thread): 
    def __init__(self, lock, state): 
     threading.Thread.__init__(self) 
     self.lock = lock 
     self.state = state    

    def run(self): 
     lock = self.lock 
     state = self.state 
     while True: 
      lock.acquire() 
      self.updateState(state) 
      lock.release() 
      time.sleep(60) 
+0

我想這樣做,但是我重寫默認參數__init__有,我不是嗎? – ddinchev

+2

http://docs.python.org/library/threading.html#threading.Thread:「如果子類重寫構造函數,它必須確保在做任何事情之前調用基類構造函數(Thread .__ init __())到線程「。 – dsign

+0

@Veseliq或者你可以引入一些getter和setter用於'StateManager' – lidaobing

7

我會說,它更容易從StateManager對象保持threading部離開:

import threading 
import time 

class StateManager(object): 
    def __init__(self, lock, state): 
     self.lock = lock 
     self.state = state 

    def run(self): 
     lock = self.lock 
     state = self.state 
     while True: 
      with lock: 
       self.updateState(state) 
       time.sleep(60) 

lock = threading.Lock() 
state = {} 
manager = StateManager(lock, state) 
thread = threading.Thread(target=manager.run) 
thread.start() 
相關問題