我创建了一个python线程。通过调用它的start()方法来运行它,我监视线程内的falg,如果该标志==True,我知道用户不再希望线程继续运行,所以我喜欢做一些内部清理并终止线程。
但是我无法终止线程。我尝试了 thread.join() 、 thread.exit() 、thread.quit() ,都抛出异常。
这是我的线程的样子。
编辑1:请注意 core() 函数是在标准 run() 函数中调用的,我在这里没有展示它。
编辑2:当 StopFlag 为 true 时,我刚刚尝试了 sys.exit() ,它看起来线程终止了!这样做安全吗?
class workingThread(Thread):
def __init__(self, gui, testCase):
Thread.__init__(self)
self.myName = Thread.getName(self)
self.start() # start the thread
def core(self,arg,f) : # Where I check the flag and run the actual code
# STOP
if (self.StopFlag == True):
if self.isAlive():
self.doHouseCleaning()
# none of following works all throw exceptions
self.exit()
self.join()
self._Thread__stop()
self._Thread_delete()
self.quit()
# Check if it's terminated or not
if not(self.isAlive()):
print self.myName + " terminated "
# PAUSE
elif (self.StopFlag == False) and not(self.isSet()):
print self.myName + " paused"
while not(self.isSet()):
pass
# RUN
elif (self.StopFlag == False) and self.isSet():
r = f(arg)
最佳答案
这里有几个问题,也可能是其他问题,但如果您没有显示整个程序或特定的异常,这是我能做的最好的:
- 线程应执行的任务应称为“run”或传递给线程构造函数。
- 线程本身不会调用 join(),启动该线程的父进程会调用 join(),这会使父进程阻塞,直到线程返回。
- 通常父进程应该调用 run()。
- 一旦完成 run() 函数(返回),线程就完成了。
简单的例子:
import threading
import time
class MyThread(threading.Thread):
def __init__(self):
super(MyThread,self).__init__()
self.count = 5
def run(self):
while self.count:
print("I'm running for %i more seconds" % self.count)
time.sleep(1)
self.count -= 1
t = MyThread()
print("Starting %s" % t)
t.start()
# do whatever you need to do while the other thread is running
t.join()
print("%s finished" % t)
输出:
Starting <MyThread(Thread-1, initial)>
I'm running for 5 more seconds
I'm running for 4 more seconds
I'm running for 3 more seconds
I'm running for 2 more seconds
I'm running for 1 more seconds
<MyThread(Thread-1, stopped 6712)> finished
关于python - 根据标志终止 python 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12648962/