我目前正在处理涉及所有使用ssh / telnet libs的线程列表的问题。我希望主线程的某个超时值指示线程关闭所有资源,并自行终止。这是我的代码看起来像
的示例import threading
import time
import socket
threads = []
def do_this(data):
"""this function is not the implementation this code may not be valid"""
w = socket.create_connection(data, 100)
while True:
if 'admin' in w.read(256):
break
w.close
for data in data_list:
t = threading.Thread(target=do_this, args=(data,))
t.start()
threads.append(t)
end_time = time.time()+120
for t in threads:
t.join(end_time-time.time())
我想做的是有一些方法来通知线程并修改线程方法,以便它做到这样的事情
def do_this(data):
w = socket.create_connection(data, 100)
while True:
if 'admin' in w.read(256):
break
w.close()
on signal:
w.close()
return
答案 0 :(得分:0)
在UNIX上,您可以使用以下答案:Timeout function if it takes too long to finish
在Windows上,它有点棘手,因为它不是signal
lib。无论如何,你只需要一个看门狗,所以超时不必是精确的:
def timeout(timeout):
sleep(XX_SECONDS)
timeout = True
def do_this(data):
"""this function is not the implementation this code may not be valid"""
timeout = False
w = socket.create_connection(data, 100)
timer = threading.Thread( target = timeout, args=(timeout,) )
while not timeout:
if 'admin' in w.read(256):
break
或者,如果您使用的是socket
lib,则可以选择非阻塞:http://docs.python.org/2/library/socket.html#socket.socket.settimeout