如何停止守护进程线程? [英] How to stop daemon thread?

查看:154
本文介绍了如何停止守护进程线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的生产者消费者应用程序.

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

和消费者

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

c完成唯一剩余的非守护进程线程为主线程时,结束这些线程的正确方法是什么?

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

更新

这是我的生产者正在使用的确切代码,因为消费者正在退出并且问题出在生产者身上

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?

推荐答案

问题是生产者循环永远不会结束,因此您应该有一种方法使其停止.

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

生产者变为:

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

这篇关于如何停止守护进程线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆