Just a learner
Just a learner

Reputation: 28622

How to properly stop python threads?

I'm new in Python. This is my code:

import logging
logging.basicConfig(level = logging.DEBUG, format = "[%(levelname)s] (%(threadName)-10s) %(message)s")
import threading
import time

def thread1():
    for i in range(0, 10, 2):
        logging.debug(i)
        time.sleep(1)


def thread2():
    for i in range(10, 20):
        logging.debug(i)
        time.sleep(1)

t1 = threading.Thread(name = "thread1", target = thread1)
t1.setDaemon(True)
t1.start()

t2 = threading.Thread(name = "thread2", target = thread2)
t2.setDaemon(True)
t2.start()

When I copied the code and pasted it into a python command line prompt, I got the following result.

enter image description here

As you can see, the 2 threads already completed but it seems the program does not exit ( I did not get the command prompt back). I think it relates to my code that did not property end the threads. Is that true? How to fixed this issue? Thanks.

Upvotes: 4

Views: 3977

Answers (2)

actionseth
actionseth

Reputation: 27

If I remember correctly -- You need to use threading.Event to stop a thread. For example:

self.stoprequest = threading.Event()

""" When self.stoprequest.set() is called,
it sets an event on the thread - stopping it.""" 
self.stoprequest.set()

So if you create a threading.Event() on each thread you start you can stop it from outside using instance.set()

You can also kill the main thread from which the child threads were spawned :)

Upvotes: 0

tdelaney
tdelaney

Reputation: 77407

Actually, the command prompt returned in the line >>> [DEBUG] (thread1 ) 2 and was ready for more input. The deamon threads ran in the background, printed the the stuff they were supposed to and finally completed. You didn't need to type ctrl-c at all. You could have just entered another python command.

Upvotes: 4

Related Questions