gpt4 book ai didi

python 和 ipython threading.activeCount()

转载 作者:太空宇宙 更新时间:2023-11-03 14:25:58 26 4
gpt4 key购买 nike

我有一个导入线程并使用 threading.activeCount() 的模块确定所有线程何时完成。我最初使用标准 python 解释器编写我的模块。在脚本中使用我的模块很好,但是在 ipython 中导入我的模块并调用依赖于 threading.activeCount() 的函数时。我的函数永远不会返回。

代码:

for dev in run_list:
proc = threading.Thread(target=go, args=[dev])
proc.start()

while threading.activeCount() > 1:
time.sleep(1)

我注意到,当第一次使用标准解释器导入线程并调用 threading.activeCount() 时,只计算了 1 个线程:

>>> import threading
>>> threading.activeCount()
1
>>> threading.enumerate()
[<_MainThread(MainThread, started 140344324941568)>]

但是当使用 ipython 时,初始计数是 2:

In [1]: import threading

In [2]: threading.activeCount()
Out[2]: 2

In [3]: threading.enumerate()
Out[3]:
[<_MainThread(MainThread, started 140674997614336)>,
<HistorySavingThread(Thread-1, started 140674935068416)>]

这个模块被各种使用各种解释器的人使用,所以我想知道是否有更好的方法来处理这个问题(最好仍然使用线程)?

最佳答案

join你的线程而不是依赖 activeCount:

threads = []
for dev in run_list:
proc = threading.Thread(target=go, args=[dev])
proc.start()
threads.append(proc)

for proc in threads:
proc.join()

关于python 和 ipython threading.activeCount(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20575746/

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