Python 检查线程/从列表中删除

Python 检查线程/从列表中删除,python,multithreading,list,Python,Multithreading,List,我有一个线程,它扩展了线程。代码看起来有点像这样 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)

我有一个线程,它扩展了线程。代码看起来有点像这样

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

您需要调用以确定线程是否仍在运行

,正如MacGuy所说,您应该使用来检查线程是否仍在运行。要从列表中删除不再运行的线程,可以使用:


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

更好的方法是使用队列类:

查看文档页面底部的好示例代码:

def worker():
    while True:
        item = q.get()
        do_work(item)
        q.task_done()

q = Queue()
for i in range(num_worker_threads):
     t = Thread(target=worker)
     t.daemon = True
     t.start()

for item in source():
    q.put(item)

q.join()       # block until all tasks are done

答案已经涵盖,但为了简单起见

# To filter out finished threads
threads = [t for t in threads if t.is_alive()]

# Same thing but for QThreads (if you are using PyQt)
threads = [t for t in threads if t.isRunning()]
枚举返回仍然活动的所有线程对象的列表。

谢谢,但这是否意味着结果可能会丢失?如果一个线程不再活动,那么我需要得到结果。这是真的。考虑到这一点,我修改了我的答案。
is_alive()
在Python 2.6+中,这比我想象的速度快得惊人。谢谢。@erm3nda不一样了。在is_alive()上使用列表理解可能会在对该线程执行“get results”块之前删除该线程。谢谢,但是我是否会遇到与q.join()相同的问题?如果我有20个工作需要做,但一次最多只想运行4个。如果3个已完成,而一个未完成,则我不想在程序等待1个结果时减慢程序的速度…
thread.isAlive()
现在已被清除,请改用
thread.is\u alive()
。这很有用……但当java中有多个非活动cild线程时该怎么办?有办法处理它们吗
def worker():
    while True:
        item = q.get()
        do_work(item)
        q.task_done()

q = Queue()
for i in range(num_worker_threads):
     t = Thread(target=worker)
     t.daemon = True
     t.start()

for item in source():
    q.put(item)

q.join()       # block until all tasks are done
# To filter out finished threads
threads = [t for t in threads if t.is_alive()]

# Same thing but for QThreads (if you are using PyQt)
threads = [t for t in threads if t.isRunning()]
mythreads = threading.enumerate()