Python 如何使用ThreadPoolExecutor递归遍历目录?
我真正的任务是使用带多线程的paramiko递归遍历远程目录。为了简单起见,我只使用本地文件系统来演示:Python 如何使用ThreadPoolExecutor递归遍历目录?,python,multithreading,python-3.x,Python,Multithreading,Python 3.x,我真正的任务是使用带多线程的paramiko递归遍历远程目录。为了简单起见,我只使用本地文件系统来演示: from pathlib import Path from typing import List from concurrent.futures import ThreadPoolExecutor, Executor def listdir(root: Path, executor: Executor) -> List[Path]: if root.is_dir():
from pathlib import Path
from typing import List
from concurrent.futures import ThreadPoolExecutor, Executor
def listdir(root: Path, executor: Executor) -> List[Path]:
if root.is_dir():
xss = executor.map(lambda d: listdir(d, executor), root.glob('*'))
return sum(xss, [])
return [root]
with ThreadPoolExecutor(4) as e:
listdir(Path('.'), e)
但是,上面的代码没有结束
我的代码怎么了?以及如何修复它(最好使用Executor
而不是原始线程
)
编辑:我已通过以下代码确认@Sraw的答案:
In [4]: def listdir(root: Path, executor: Executor) -> List[Path]:
...: print(f'Enter {root}', flush=True)
...: if root.is_dir():
...: xss = executor.map(lambda d: listdir(d, executor), root.glob('*'))
...: return sum(xss, [])
...: return [root]
...:
In [5]: with ThreadPoolExecutor(4) as e:
...: listdir(Path('.'), e)
...:
Enter .
Enter NonRestrictedShares
Enter corporateActionData
Enter RiskModelAnnualEPS
Enter juyuan
你的代码中有一个死锁 当您使用
线程池执行器(4)
时,此执行器中只有四个工作线程,因此您不能同时运行四个以上的任务
想象一下以下最简单的结构:
test
----script.py
----test1
--------test2
------------test3
----------------test4
--------------------test5
如果pythonscript.py
,第一个工作线程处理test1
,第二个工作线程处理test1/test2
,第三个工作线程处理test1/test2/test3
,第四个工作线程处理test1/test2/test3/test4
。现在,工作线程已耗尽。但在工作队列中插入了另一个任务test1/test2/test3/test4/test5
所以它将永远挂起。谢谢,有没有简单的方法来修复我的代码?我想知道我是否可以使用
Executor.submit
而不是Executor.map
来避免死锁。不,submit
不会解决这个问题。但我认为您只能在顶部目录中使用executor
,这样所有任务都是独立的。这不是一个完美的解决方案,但却是最简单的一个,我认为它对于大多数情况来说也足够好了。