gpt4 book ai didi

python - 根据标志退出 Python 线程

转载 作者:行者123 更新时间:2023-11-28 22:01:42 25 4
gpt4 key购买 nike

假设在 python Thread 的 run() 方法中,我检查一个标志。如果该标志为 True ,我假设我的线程应该退出已经完成它的工作并且应该退出。

那时我应该如何退出线程?尝试 Thread.exit()

class  workingThread(Thread):

def __init__(self, flag):
Thread.__init__(self)
self.myName = Thread.getName(self)
self.FLAG= flag
self.start() # start the thread

def run(self) : # Where I check the flag and run the actual code

# STOP
if (self.FLAG == True):

# none of following works all throw exceptions
self.exit()
self._Thread__stop()
self._Thread_delete()
self.quit()

# RUN
elif (self.FLAG == False) :
print str(self.myName)+ " is running."

最佳答案

korylprince 是正确的。您只需要一个返回语句,或者在您的情况下通过:

def run(self):
if self.FLAG == True:
pass
else:
print str(self.myName) + " is running."

由于代码中没有循环结构,线程将在两种情况下终止。基本上一旦函数返回,线程就会退出。如果您想执行多个操作,请在其中添加某种循环。

关于python - 根据标志退出 Python 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12678750/

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