2011-12-07 34 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() 
相关问题