How to stop daemon thread?

左心房为你撑大大i 提交于 2019-12-03 10:01:21

问题


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?


回答1:


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()


来源:https://stackoverflow.com/questions/41131117/how-to-stop-daemon-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!