gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:43:53 24 4
gpt4 key购买 nike

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

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

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

最佳答案

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

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)

关于Python:将参数传递给 threading.Thread 实例的正确方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8418067/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com