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

ddi*_*hev 4 python multithreading

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

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

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

lid*_*ing 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)
Run Code Online (Sandbox Code Playgroud)

  • http://docs.python.org/library/threading.html#threading.Thread:"如果子类重写构造函数,它必须确保在执行任何其他操作之前调用基类构造函数(Thread .__ init __())线程." (2认同)

jco*_*ado 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()
Run Code Online (Sandbox Code Playgroud)