在Python中维护线程的自动清除列表

问题描述 投票:2回答:2

我维护一个threads列表,我想完成后自动从列表中删除线程

我发现此方法:

import threading, time

def f(seconds, info):
    print('starting', seconds)
    time.sleep(seconds)
    print('finished', seconds)
    threads.remove(info['thread'])

def newaction(seconds):
    info = {}
    thread = threading.Thread(target=f, args=(seconds, info))
    info['thread'] = thread
    thread.start()
    threads.append(thread)

threads = []
newaction(1)
newaction(2)
for _ in range(10):
    time.sleep(0.3)
    print(threads)

有效:

starting 1
starting 2
[<Thread(Thread-1, started 1612)>, <Thread(Thread-2, started 712)>]
[<Thread(Thread-1, started 1612)>, <Thread(Thread-2, started 712)>]
[<Thread(Thread-1, started 1612)>, <Thread(Thread-2, started 712)>]
finished 1
[<Thread(Thread-2, started 712)>]
[<Thread(Thread-2, started 712)>]
[<Thread(Thread-2, started 712)>]
finished 2
[]
[]
[]
[]

但是必须通过字典info的事实有点可笑。我使用它是因为显然我无法在thread ...中传递args ...

thread = threading.Thread(target=f, args=(seconds, thread))  
#                                                     ^ not created yet!

...当尚未创建Thread对象时!

Python中是否有更自然的方法来维护线程的自动清除列表?

我维护一个线程列表,我想在完成线程后从列表中自动删除线程。我发现了这种方法:导入线程,时间def f(秒,信息):print('starting',seconds)...

python multithreading python-multithreading
2个回答
1
投票

您具有current_thread()功能。


0
投票
import threading

def get_status_of_threads():
    current_threads = threading.enumerate()

    thread_data = []

    for item in current_threads:
        try:
            print(str(item.target))
        except AttributeError:
            print("item", str(item))
        thread_data.append({"thread_name": item.getName(), "status": int(item.is_alive()), "id": item.ident})
    return thread_data

© www.soinside.com 2019 - 2024. All rights reserved.