Python:将参数传递给threading.Thread实例的正确方法是什么

时间:2011-12-07 15:41:43

标签: python multithreading

我已经扩展了线程。线程 - 我的想法是做这样的事情:

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

我需要能够将引用传递给我的“状态”对象并最终传递给一个锁(我对多线程很新,并且仍然对在Python中锁定的必要性感到困惑)。这样做的正确方法是什么?

2 个答案:

答案 0 :(得分:8)

在构造函数中传递它们,例如

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)

答案 1 :(得分:8)

我说保持threading部分远离StateManager对象更容易:

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()