簡體   English   中英

如何在Python中的線程中停止for循環?

[英]How to stop a for loop in a thread in Python?

我試圖在Python中創建一個腳本來學習線程,但似乎無法停止線程中的for循環。 目前,我正在使用pyInstaller編譯腳本並結束Thread進程,我知道這不是最好的方法,有人可以向我解釋如何在命令中結束線程嗎? 我已經閱讀了許多其他問題,但是我似乎無法理解如何以“正確”的方式停止線程。 這是到目前為止我正在使用的代碼進行測試:

class Thread(Thread):
        def __init__(self, command, call_back):
        self._command = command
        self._call_back = call_back
        super(Thread, self).__init__()

    def run(self):
        self._command()
        self._call_back()
def test():
    i = 20
    for n in range(0,i):
        #This is to keep the output at a constant speed
        sleep(.5)
        print n
def thread_stop():
    procs = str(os.getpid())
    PROCNAME = 'spam.exe'
    for proc in psutil.process_iter():
        if proc.name == PROCNAME:
            text = str(proc)[19:]
            head, sep, tail = text.partition(',')
            if str(head) != procs:
                subprocess.call(['taskkill', '/PID', str(head), '/F'])

這些功能由Tkinter中的GUI調用,目前還不錯。

如果您不想閱讀所有內容,請直達這一點:當Python中的線程中存在for循環時,如何以“正確的方式”停止線程? 謝謝!

編輯:抱歉,我取消了我認為最重要的代碼。 相反,這是完整的代碼(這是我用來學習Python的文本消息器,但是以上是我開始理解之前的第一次嘗試線程化)。 http://pastebin.com/qaPux1yR

您永遠不應強行殺死線程。 而是使用某種線程定期檢查的“信號”,如果設置了該信號,則線程會順利完成。

最簡單的“信號”類型是一個簡單的布爾變量,可以像這樣使用:

class MyThread(Thread):
    def __init__(self):
        self.continue = True

    def run(self):
        while (self.continue):
            # Do usefull stuff here
            pass

    def stop(self):
        self.continue = False

暫無
暫無

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

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