Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
基于标志终止python线程_Python_Multithreading - Fatal编程技术网

基于标志终止python线程

基于标志终止python线程,python,multithreading,Python,Multithreading,我创建了一个python线程,当调用它的start()方法开始运行时,我监视线程中的一个falg,如果该标志==True,我知道用户不再希望线程继续运行,所以我决定做一些内部清理并终止线程 然而,我无法终止线程。我尝试了thread.join()、thread.exit()、thread.quit()、所有抛出异常 这是我的线的样子 编辑1:请注意core()函数是在标准run()函数中调用的,我在这里没有显示 编辑2:当StopFlag为true时,我刚刚尝试了sys.exit(),看起来线程

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

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

  • 线程应该执行的任务应该称为“运行”或传递给线程构造函数
  • 线程本身不调用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
    
    启动
    我还要跑5秒钟
    我还要跑4秒钟
    我还要跑3秒钟
    我还要跑两秒钟
    我还要跑1秒钟
    完成
    
    没有明确的方法来终止线程,无论是从对线程实例的引用还是从线程模块

    也就是说,运行多个线程的常见用例确实允许有机会阻止它们无限期地运行。例如,如果您通过与外部资源建立连接,则始终可以指定超时:

    import urllib2
    urllib2.urlopen(url[, data][, timeout])
    
    套接字也是如此:

    import socket
    socket.setdefaulttimeout(timeout)
    
    请注意,在指定超时的情况下调用线程的join([timeout])方法只会阻塞hte timeout(或直到线程终止。它不会终止线程)


    如果要确保线程在程序完成时终止,只需确保在调用线程对象的start()方法之前将其daemon属性设置为True即可。

    感谢您的更正。假设内部运行(),我检查一个标志。如果该标志为真,我假设我的线程应该退出已经完成了它的工作,应该退出。怎么做?谁在设置,谁在检查?如果主程序决定终止线程,它可以设置标志。然后线程会看到标志已经设置,并从run()函数返回。主线程可以join()等待它的线程检查标志并终止。一旦线程完成,它将从该调用返回。如果线程本身已完成其任务,它只从run()函数返回。就这么简单。