Python 指示线程关闭资源

Python 指示线程关闭资源,python,multithreading,Python,Multithreading,我目前正在处理一个涉及所有使用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.c

我目前正在处理一个涉及所有使用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())
我想做的是有一些方法来向线程发送信号,并修改thread方法,这样它就可以做这样的事情

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

在UNIX上,您可以使用以下答案:

在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,那么它们有一个非阻塞选项:

为了澄清,在第二个关闭块中,您希望
on signal
终止线程吗?