gpt4 book ai didi

python - 队列中的所有任务已完成,但程序未继续

转载 作者:行者123 更新时间:2023-11-28 21:51:42 29 4
gpt4 key购买 nike

我有一个这样定义的线程类:

#!/usr/bin/python

import threading
import subprocess

class PingThread (threading.Thread):
ipstatus = ''
def __init__(self, ip):
threading.Thread.__init__(self)
self.ipaddress = ip


def ping(self, ip):
print 'Pinging ' + ip + '...'
ping_response = subprocess.Popen(["ping", "-c", "1", ip], stdout=subprocess.PIPE).stdout.read()
if '100.0% packet loss' not in str(ping_response):
return True
return False

def set_ip_status(self, status):
self.ipstatus = status

def get_ip_status(self):
return self.ipstatus

def run(self):
self.ipaddress = self.ipaddress.strip('\n\t')
pingResponse = self.ping(self.ipaddress)
if pingResponse:
self.set_ip_status(self.ipaddress + ' is up!')
else:
self.set_ip_status(self.ipaddress + ' is down!')

我正在查看一个 IP 地址列表并将其发送到 PingThread 并让此类对 IP 地址执行 ping 操作。当这些线程都完成后,我希望它通过并通过调用 get_ip_status() 获取每个线程的状态。我的代码中有 q.join(),它应该等到队列中的所有项目都完成(根据我的理解,如果我错了请纠正我,对线程仍然是新手)但是我的代码从未通过 q.join。我进行了测试,所有线程都完成了,所有 ip 地址都被 ping 了,但是 q.join() 没有识别出来。为什么是这样?我究竟做错了什么?我正在创建这样的线程:

q = Queue.Queue()
for ip in trainips:
thread = PingThread(ip)
thread.start()
q.put(thread)
q.join()
while not q.empty():
print q.get().get_ip_status()

最佳答案

您误解了 Queue.join 的工作原理。 Queue.join 旨在与 Queue.task_done 一起使用;在生产者端,您在一端 项目放入Queue,然后调用Queue.join 等待所有项目put 待处理。然后在消费者端,您从 Queue获取 一个项目,处理它,然后在完成后调用 Queue.task_done。一旦 task_done 已被 putQueue 的所有项目调用,Queue.join 将解除阻塞.

但你没有这样做。您只是启动了一堆线程,将它们添加到 Queue,然后对其调用 join。您根本没有使用 task_done,您只是在 Queue.join 之后调用了 Queue.get,看起来您我们只是在完成后使用它来获取线程对象。但事实并非如此。 Queue 不知道其中有一个 Thread 对象,简单地调用 Queue.join 不会等待 Thread 里面的对象来完成。

真的,看起来您需要做的就是将线程放入列表中,然后在每个线程上调用 join

threads = []
for ip in trainips:
thread = PingThread(ip)
thread.start()
threads.append(thread)
for thread in threads:
thread.join()
print thread.get_ip_status()

关于python - 队列中的所有任务已完成,但程序未继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29703168/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com