python和ipython threading.activeCount()

2024-09-25 00:22:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个导入线程的模块,它使用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)>]

这个模块被不同的人使用,他们使用不同的解释器来工作,所以我想知道是否有更好的方法来处理这个问题(最好还是使用线程)?


Tags: 模块函数indevimport标准ipythonproc