在“while True”循环中的线程化

3
首先,我只是一个月前开始接触 Python,所以对任何事情都没有深入的了解。
在一个项目中,我试图将多个(同时进行)函数的结果无限制地收集到数据库中,直到我告诉它停止为止。在早期的尝试中,我成功地使用了多进程来完成我需要的功能,但由于我现在需要在主函数中收集所有这些函数的结果到数据库中,所以我改用了线程。
基本上,我要做的就是:
collect1 = Thread(target=collect_data1)
collect2 = Thread(target=collect_data2)
send1 = Thread(target=send_data1)
send2 = Thread(target=send_data2)
collect = (collect1, collect2)
send = (send1, send2)
while True:
    try:
        for thread in collect:
            thread.start()
        for thread in collect:
            thread.join()
        for thread in send:
            thread.start()
        for thread in send:
            thread.join()
    except KeyboardInterrupt:
        break

显然我不能仅仅重启线程,也不能明确地杀死它们。在线程内的函数理论上可以在任何时候停止,因此使用multiprocessing中的terminate()就很好。

我在想是否像下面这样可以工作(至少PyCharm可以接受,所以似乎可以工作),或者它会创建一个内存泄漏(我认为是),因为线程从未被正确关闭或删除,至少根据我的研究结果是这样的。 再次说明,我对Python还不熟悉,对于这个方面的事情一无所知。

代码:

while True:
        try:
            collect1 = Thread(target=collect_data1)
            collect2 = Thread(target=collect_data2)
            send1 = Thread(target=send_data1)
            send2 = Thread(target=send_data2)
            collect = (collect1, collect2)
            send = (send1, send2)
            for thread in collect:
                thread.start()
            for thread in collect:
                thread.join()
            for thread in send:
                thread.start()
            for thread in send:
                thread.join()
        except KeyboardInterrupt:
            break

我觉得这种方法似乎过于完美,尤其是在我的研究中从未遇到过类似的解决方案。

无论如何,欢迎提供任何意见。

祝你有愉快的一天。


thread.join()足以终止线程。"因为线程从未被正确关闭或删除"的意思是什么? - rdas
也许这只是我来自c++背景的个人习惯,试图清理自己的代码。感谢你的建议。 - amentetcircle
1个回答

3
你需要在循环中使用thread.join()明确等待线程终止,以避免内存泄漏,这样你的代码就可以正常运行。如果你担心在线程结束后没有以任何方式处理线程对象,那么当它们不再使用时会自动完成处理,所以这也不应该成为一个问题。

谢谢,这正是我所希望发生的事情,但我无法明确地找到任何地方 :) - amentetcircle

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接