检查线程/从列表中删除 [英] Checking on a thread / remove from list

查看:64
本文介绍了检查线程/从列表中删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个扩展Thread的线程.代码看起来像这样;

I have a thread which extends Thread. The code looks a little like this;

class MyThread(Thread):
    def run(self):
        # Do stuff

my_threads = []
while has_jobs() and len(my_threads) < 5:
    new_thread = MyThread(next_job_details())
    new_thread.run()
    my_threads.append(new_thread)

for my_thread in my_threads
    my_thread.join()
    # Do stuff

因此,在我的伪代码中,我检查是否有任何作业(例如db等)以及是否有一些作业,并且如果正在运行的线程少于5个,请创建新线程.

So here in my pseudo code I check to see if there is any jobs (like a db etc) and if there is some jobs, and if there is less than 5 threads running, create new threads.

因此,从这里开始,我检查线程,这是我被卡住的地方,我可以使用.join(),但是我的理解是-这会一直等到完成,以便检查的第一个线程是否仍在进度,然后等待直到完成-即使其他线程已经完成....

So from here, I then check over my threads and this is where I get stuck, I can use .join() but my understanding is that - this then waits until it's finished so if the first thread it checks is still in progress, it then waits till it's done - even if the other threads are finished....

那么有没有一种方法可以检查线程是否完成,如果可以,则将其删除?

so is there a way to check if a thread is done, then remove it if so?

例如

for my_thread in my_threads:
    if my_thread.done():
        # process results
        del (my_threads[my_thread]) ?? will that work...

推荐答案

正如TokenMacGuy所说,您应该使用列表理解 :

As TokenMacGuy says, you should use thread.isAlive() to check if a thread is still running. To remove no longer running threads from your list you can use a list comprehension:

for t in my_threads:
    if not t.isAlive():
        # get results from thtead
        t.handled = True
my_threads = [t for t in my_threads if not t.handled]

这避免了在迭代列表时从列表中删除项目的问题.

This avoids the problem of removing items from a list while iterating over it.

这篇关于检查线程/从列表中删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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