Stopping a python thread running an Infinite Loop

前端 未结 2 1025
[愿得一人]
[愿得一人] 2021-01-12 10:44

I am new to python programming. I am trying to make a GUI with stoppable threads. I borrowed some code from https://stackoverflow.com/a/325528

class MyThre         


        
相关标签:
2条回答
  • 2021-01-12 11:10

    I think you missed the 'The thread itself has to check regularly for the stopped() condition' bit of that documentation.

    Your thread needs to run like this:

    while not self.stopped():
        # do stuff
    

    rather than while true. Note that it is still only going to exit at the 'start' of a loop, when it checks the condition. If whatever is in that loop is long-running, that may cause unexpected delays.

    0 讨论(0)
  • 2021-01-12 11:15
    import threading
    import time
    class MultiThreading:
    
        def __init__(self):
            self.thread = None
            self.started = True
        def threaded_program(self):
            while self.started:
                print("running")
                # time.sleep(10)
        def run(self):
            self.thread = threading.Thread(target=self.threaded_program, args=())
            self.thread.start()
        def stop(self):
            self.started = False
            self.thread.join()
    
    0 讨论(0)
提交回复
热议问题