我有一个产生线程的服务。
通过提供目标函数来启动线程。
当函数结束时,线程似乎不会“死亡”。我知道这一点是因为线程与Paramiko建立了一些 SSH 连接(通过Fabric),如果我这样做,lsof我会看到 SSH 连接在函数完成后仍然处于活动状态。
如何确保线程在其目标函数完成时死亡?
这是我正在使用的示例:
from time import sleep
from threading import Thread
from fabric.api import run, settings
def thread_func(host):
    with settings(host_string=host):
        run('ls -lht /tmp')
def spawn_thread(host):
    t = Thread(
        target=thread_func,
        args=(host,)
    )
    t.start()
spawn_thread('node1.example.com')
while True:
    sleep(1)
如果我sudo lsof | grep ssh在上面的代码处于无限循环中时在另一个终端中运行,我会看到以下内容,即使我知道线程不应该再存在:
python    6924      daharon    3u     IPv4             170520        0t0        TCP 10.1.1.173:47368->node1.example.com:ssh (ESTABLISHED)
python    6924      daharon    5u     IPv4             170524        0t0        TCP 10.1.1.173:47369->node1.example.com:ssh (ESTABLISHED)
python    6924 6930 daharon    3u     IPv4             170520        0t0        TCP 10.1.1.173:47368->node1.example.com:ssh (ESTABLISHED)
python    6924 6930 daharon    5u     IPv4             170524        0t0        TCP 10.1.1.173:47369->node1.example.com:ssh (ESTABLISHED)
python    6924 6932 daharon    3u     IPv4             170520        0t0        TCP 10.1.1.173:47368->node1.example.com:ssh (ESTABLISHED)
python    6924 6932 daharon    5u     IPv4             170524        0t0        TCP 10.1.1.173:47369->node1.example.com:ssh (ESTABLISHED)