Python 当某个变量设置为true时,立即终止线程
当某个变量值设置为true时,如何终止线程Python 当某个变量设置为true时,立即终止线程,python,multithreading,Python,Multithreading,当某个变量值设置为true时,如何终止线程 import threading class test(threading.Thread): def __init__(self): self.stopThread = False self.start(): def start(self): while not self.stopThread: callOtherFunction //which
import threading
class test(threading.Thread):
def __init__(self):
self.stopThread = False
self.start():
def start(self):
while not self.stopThread:
callOtherFunction //which takes alomst 30 sec to execute
def stop(self):
self.stopThread = True
现在的问题是,如果调用了start函数,并且在循环启动时,它将在下一次迭代中检查停止条件,当它完成内部工作时,因此如果调用callOtherFunction,那么它仍将等待30秒退出。。我想在设置变量时立即终止线程。有可能吗?这里回答了这个问题: 底线是,如果你能帮助它,你应该避免这样杀死一个线程。然而,如果你必须的话,你可以尝试一些技巧
此外,为了线程安全,您应该使
self.stopThread
athreading.Event()
,并使用set()
和clear()
来通知何时应该停止线程。如果您想立即终止线程,则应该使用多处理