繁体   English   中英

在“while True”循环中线程化

[英]Threading in 'while True' loop

首先,我一个月前才开始使用 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

现在,显然我不能只是重新启动线程。 也不明确杀死他们。 理论上,线程中的函数可以随时停止,因此多处理中的 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()循环中明确等待线程的终止,因此不会发生内存泄漏,并且您的代码很好。 如果您担心在线程对象终止后不以任何方式处理它们,一旦不再使用它们就会自动完成,因此这也不必担心。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM