gpt4 book ai didi

python - 在 Python 中维护一个可自动清理的线程列表

转载 作者:行者123 更新时间:2023-12-03 12:44:47 27 4
gpt4 key购买 nike

我维护了一个 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有点黑客。我用它是因为显然我不能通过 threadargs ...
thread = threading.Thread(target=f, args=(seconds, thread))  
# ^ not created yet!

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

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

最佳答案

您有 current_thread()功能。

import threading, time

def f(seconds):
print('starting', seconds)
time.sleep(seconds)
print('finished', seconds)
threads.remove(threading.current_thread())

def newaction(seconds):
thread = threading.Thread(target=f, args=(seconds,))
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 4588)>, <Thread(Thread-2, started 4388)>]
[<Thread(Thread-1, started 4588)>, <Thread(Thread-2, started 4388)>]
[<Thread(Thread-1, started 4588)>, <Thread(Thread-2, started 4388)>]
finished 1
[<Thread(Thread-2, started 4388)>]
[<Thread(Thread-2, started 4388)>]
[<Thread(Thread-2, started 4388)>]
finished 2
[]
[]
[]
[]

关于python - 在 Python 中维护一个可自动清理的线程列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62060064/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com