我认为学习使用线程的最简单方法是在concurrent.futures模块中使用ThreadPoolExecutor类,因为它比通常的同步for循环多了几行。尤其是在Python3中,但这可以适用于Python2.7。在
基本上你有一个线程池(一堆)等待工作。Work通常只是一个方法/函数,它与参数一起发送到池,ThreadPool处理其他所有事情(将任务分配给可用的资源并进行调度)。在
假设我的日志目录结构如下:~ ❯ tree log
log
├── 1.log
├── 2.log
├── 3.log
└── schedules
├── 1.log
├── 2.log
└── 3.log
1 directory, 6 files
因此,首先得到文件列表(Python3)。在
^{pr2}$
每个文件(现在只是一个字符串变量)就是你希望线程处理的。因此,您有一个通用方法,接受一个file参数,在每个文件中找到感兴趣的字符串。基本上是一样的,如果你做了一个普通的Python程序,比如:def find_string(file):
# insert your specific code to find your string
# including opening the file and such
# returning values also possible see further down
print(file)
现在您只需将这些工作发送到ThreadPool。在from concurrent.futures import ThreadPoolExecutor
# We c