XD blog

blog page

python, thread


2013-11-02 Stop a thread in Python

I was writing a simple GUI in Python, a button start to start a function from a thread, another one to stop the execution. I then realized my program did not stop.

import threading, time

class MyThread(threading.Thread):
    def run(self):
        while True:
            time.sleep(1)
            
th = MyThread()
th.start()

There are two ways to avoid that issue. The first one is to set up daemon to True.

th = MyThread()
th.daemon = True
th.start()

The second way is to use a kind of hidden function _stop(not documented). But this function might disappear in the next version of python.

th = MyThread()
th.start()
th._stop()

<-- -->

Xavier Dupré