Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python3如何从列表中删除线程对象_Python_Multithreading_List - Fatal编程技术网

python3如何从列表中删除线程对象

python3如何从列表中删除线程对象,python,multithreading,list,Python,Multithreading,List,我正在编写一个脚本,它应该无限期地运行,并使用线程技术每隔几秒钟将一些内容放入数据库中。这是可行的,但我看到进程的内存每隔几秒钟就会略微增加,我认为这是因为保存所有线程对象的列表从未清空。我该怎么做? 连接被置于is_alive条件下,因此它不会花费任何时间来生成下一个线程。 下面的示例将导致 AttributeError:“线程”对象没有属性“kill” 我希望输出为: 11 11 最后一行(-loop和on的)可以简单地写为: threads_alive = [] for t

我正在编写一个脚本,它应该无限期地运行,并使用线程技术每隔几秒钟将一些内容放入数据库中。这是可行的,但我看到进程的内存每隔几秒钟就会略微增加,我认为这是因为保存所有线程对象的列表从未清空。我该怎么做? 连接被置于is_alive条件下,因此它不会花费任何时间来生成下一个线程。 下面的示例将导致

AttributeError:“线程”对象没有属性“kill”

我希望输出为:

11

11

最后一行(-loop和on的
)可以简单地写为:

    threads_alive = []
    for t in threads:
        if t.is_alive() == False:
            t.join()
        else:
            threads_alive.append(t)

    threads = threads_alive
或者,如果您必须以某种方式处理已经失效的线程:

    threads_alive = []
    threads_dead = []
    for t in threads:
        if t.is_alive() == False:
            t.join()
            threads_dead.append(t)
        else:
            threads_alive.append(t)

    threads = threads_alive
    for t in threads_dead:
        ... postprocess dead threads here ...

您不想加入while循环吗?使用循环或列表理解来筛选不再活动的线程,而不是为每个
x
创建一个新线程。您可能想创建一个固定的线程池(线程池)并在它们之间共享工作。@cᴏʟᴅsᴘᴇᴇᴅ 这样做会不会延迟创建以下线程?@MichaelButscher我尝试过这样做,回答如下#1:但它对我不起作用。我假设它是python2的东西?我用enumerate按索引存储死线程,因为我需要它来将其从列表中删除,但我的解决方案大致相同。谢谢
    threads_alive = []
    threads_dead = []
    for t in threads:
        if t.is_alive() == False:
            t.join()
            threads_dead.append(t)
        else:
            threads_alive.append(t)

    threads = threads_alive
    for t in threads_dead:
        ... postprocess dead threads here ...