Python:如何正确传递参数给threading.Thread实例

4 投票
2 回答
10576 浏览
提问于 2025-04-17 07:54

我扩展了 threading.Thread 类,想要实现一些功能:

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

我需要能够传递一个对我的“状态”对象的引用,最后还要传递一个锁(我对多线程还很陌生,对 Python 中锁的必要性也有些困惑)。这样做的正确方法是什么呢?

2 个回答

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

撰写回答