python和ipython threading.activeCount()

sie*_*sta 3 python multithreading ipython

我有一个导入线程并使用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)
Run Code Online (Sandbox Code Playgroud)

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

>>> import threading
>>> threading.activeCount()
1
>>> threading.enumerate()
[<_MainThread(MainThread, started 140344324941568)>]
Run Code Online (Sandbox Code Playgroud)

但是,使用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)>]
Run Code Online (Sandbox Code Playgroud)

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

Jan*_*ila 5

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()
Run Code Online (Sandbox Code Playgroud)