gpt4 book ai didi

python - 向 Python Thread 类添加新方法是否安全?

转载 作者:行者123 更新时间:2023-11-28 18:50:48 27 4
gpt4 key购买 nike

我想向 Thread 子类添加一个新方法,这样我就可以告诉我的工作线程优雅地退出。像这样:

class MyThread(threading.Thread):
def __init__(self):
...
self.__stop_signal = False
self.__signal_lock = threading.Lock()
...

def run(self):
...
self.__signal_lock.acquire(True)
stop_signal = self.__stop_signal
self.__signal_lock.release()
if stop_signal:
return
...

def stop_elegantly(self):
self.__signal_lock.acquire(True)
self.__stop_signal = True
self.__signal_lock.release()

那么这样做安全吗?

thread = MyThread()
thread.start()
...
thread.stop_elegantly()

谢谢。

最佳答案

是的,看起来不错。事实上,你可以更“优雅地”做到这一点:

def stop_elegantly(self):
with self.__signal_lock:
self.__stop_signal = True

实际上,我认为您甚至不需要锁来访问成员变量,因为将为子类的每个实例分配一个单独的锁。看这个answer例如,它向 threading.Thread 子类添加了一个 stop() 方法。

关于python - 向 Python Thread 类添加新方法是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13300877/

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