How to stop daemon thread?

LetsPlayYahtzee picture LetsPlayYahtzee · Dec 13, 2016 · Viewed 16.4k times · Source

I have a simple producer consumer application.

The producer is a thread that writes stuff to a queue and a consumer is a thread that reads the messages from the queue does stuff and at some points exits.

my producer looks a little bit like this

def producer(queue):
    while not queue.full():
        queue.put(randint(1, 199))

and the consumer

def consumer(queue):
    for i in range(100):
        print(queue.get())
        queue.task_done()

in my main I invoke those threads like that

p = Thread(target=producer)
c = Thread(target=consumer)

p.daemon = True
p.start()
c.start()
c.join()

when c finishes the only remaining non deamon thread is main, what is the proper way to end those threads?

update

Here is the exact code that my producer is using, since the consumer is exiting and the problem lies with the producer

def generate_random_alphanumerics(msg_queue):
    while True:
        if not msg_queue.full():
            msg_queue.put(hashlib.sha1(bytes(randint(1, 10000))).hexdigest() * 10)
        else:
            sleep(0.01)

is the problem that the thread is sleeping?

Answer

enrico.bacis picture enrico.bacis · Dec 14, 2016

The problem is that the producer loop never ends, so you should have a way to tell it to stop.

stop_event= threading.Event()
p = Thread(target=producer, args=(msg_queue, stop_event))
p.start()

And the producer becomes:

def generate_random_alphanumerics(msg_queue, stop_event):
    while not stop_event.is_set():
        if not msg_queue.full():
            [...]

Then, when you want to stop the producer just do:

stop_event.set()