簡體   English   中英

如何停止這個正在運行的threading.Thread?

[英]How to stop this running threading.Thread?

我在堆棧溢出中發現了這個非阻塞代碼,它使用線程在 JavaScript 中提供非阻塞 setInterval 函數的功能 但是當我嘗試停止該過程時,它甚至 Ctrl + C 都沒有停止它,我嘗試了更多方法來停止該過程,但它們不起作用。 有人可以告訴一個正確的方法來停止這個過程,提前謝謝你。

這是代碼

import threading

class ThreadJob(threading.Thread):
    def __init__(self,callback,event,interval):
        '''runs the callback function after interval seconds

        :param callback:  callback function to invoke
        :param event: external event for controlling the update operation
        :param interval: time in seconds after which are required to fire the callback
        :type callback: function
        :type interval: int
        '''
        self.callback = callback
        self.event = event
        self.interval = interval
        super(ThreadJob,self).__init__()

    def run(self):
        while not self.event.wait(self.interval):
            self.callback()



event = threading.Event()

def foo():
    print ("hello")

def boo():
    print ("fello")



def run():
    try:
        k = ThreadJob(foo,event,2)
        d = ThreadJob(boo,event,6)
        k.start()
        d.start()
        while 1:
            falg = input("Press q to quit")
            if(falg == 'q'):
                quit()
                return 
    except KeyboardInterrupt:
        print('Stoping the script...')         
    except Exception as e:
        print(e)

run()
print( "It is non-blocking")

您需要做的就是替換這一行:

quit()

有了這個:

event.set()

如果有線程仍在運行,Python 程序將不會退出,因此 quit() 函數沒有做任何事情。 一旦設置了事件的內部標志,線程將退出它們的 while 循環,因此對 event.set() 的調用將導致您創建的兩個額外線程的終止。 然后程序將退出。

注意:從技術上講,您可以將線程設置為“守護進程”,然后它們不會使程序保持活動狀態。 但我認為這不是正確的解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM