我的程序有问题。
我设法找到了问题的根源。问题出在“checkPort”方法中。没有它,用于关闭/终止线程的标准教科书方法效果很好。
我错过了什么吗?checkPort 方法中是否有阻止成功加入线程的东西?它总是卡在thread.join()
。
部分主程序:
try:
queue = Queue.Queue()
for i in range(MAX_THREAD_COUNT):
t = checkPort_IPv6_thread(queue)
t.daemon = True
threads.append(t)
t.start()
cur.execute("SELECT * FROM ipv6")
results = cur.fetchall()
for row in results:
queue.put((row[0], row[2]))
queue.join()
for thread in threads:
thread.stop()
thread.join()
except Exception as e:
sys.stderr.write("Error: " + str(e))
print
print "\nChecking ports for IPv6 - DONE"
这是我调用 checkPort 方法的线程类:
class checkPort_IPv6_thread(threading.Thread):
def __init__(self,queue):
threading.Thread.__init__(self)
self.queue = queue
self.keepRunning = True
def run(self):
while self.keepRunning:
args = self.queue.get()
id = args[0]
address = args[1]
port443 = 0
port21 = 0
port80 = 0
#---------------- Check ports for IPv6 ----------------
if str(address) != "N/A":
port443 = checkPort("TCP",str(address), 443)
port21 = checkPort("TCP",str(address), 21)
port80 = checkPort("TCP",str(address), 80)
lock.acquire()
try:
cur.execute("UPDATE ipv6 SET port_443=" + str(port443) + " WHERE id_ipv6 =" + str(id))
cur.execute("UPDATE ipv6 SET port_21=" + str(port21) + " WHERE id_ipv6 =" + str(id))
cur.execute("UPDATE ipv6 SET port_80=" + str(port80) + " WHERE id_ipv6 =" + str(id))
db.commit()
except Exception as e:
sys.stderr.write("Error: " + str(e))
except:
db.rollback()
lock.release()
self.queue.task_done()
def stop(self):
self.keepRunning = False
和checkPort 方法:
def checkPort(typ, address, port):
if typ == "TCP":
s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
else:
s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
pom = 0 # 0/1 = True/False
try:
s.settimeout(2) # timeout 1.5 sekundy
s.connect((str(address), port))
s.settimeout(None)
#time.sleep(0.5)
pom = 1
print str(address) + " >> on port: " + str(port) + " >> Connection was successfull"
except socket.timeout:
print str(address) + " >> on port: " + str(port) + " >> * Error: Timed out *"
except socket.error as e:
if e.errno == 10061:
print str(address) + " >> on port: " + str(port) + " >> * No connection could be made - target machine refused it *"
except Exception as ex:
sys.stderr.write("Error: " + str(ex))
return pom