Python:向threading.Thread instan传递参数的正确方法是什么

2024-05-17 05:43:15 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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


Tags: runselftruelockreleasedef线程thread
2条回答

我想说,让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()

将它们传递给构造函数,例如

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)

相关问题 更多 >