python - 根据标志终止 python 线程

标签 python multithreading

我创建了一个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)            

最佳答案

这里有几个问题,也可能是其他问题,但如果您没有显示整个程序或特定的异常,这是我能做的最好的:

  1. 线程应执行的任务应称为“run”或传递给线程构造函数。
  2. 线程本身不会调用 join(),启动该线程的父进程会调用 join(),这会使父进程阻塞,直到线程返回。
  3. 通常父进程应该调用 run()。
  4. 一旦完成 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/

相关文章:

database - Python:来自 CSV 数据的惰性数据库?

python - 拥有许多不同的数据类型有什么好处?

python - 忽略 python 中的 SonarQube 警告

c# - 在 C# 中线程化 2 个 Web 服务调用和组合结果数据的最佳方法是什么?

python - 计算非唯一数组元素的顺序

python - 编写程序/脚本以从一堆文件名的开头删除相同的字符串的最简单方法是什么?

python - Python + Twisted 中的消息队列代理

java - 如何让 main 方法等待 GUI 上的输入而不使用 Listener 作为直接触发器?

c# - 从 Internet 下载图像时在 C# 中使用多线程

c - C 中使用多个分离线程的内存泄漏