您现在的位置是:主页 > news > 网站集约化建设推进情况/广东省疫情最新
网站集约化建设推进情况/广东省疫情最新
admin2025/5/4 23:04:37【news】
简介网站集约化建设推进情况,广东省疫情最新,邢台市住建局,怎么再贴吧给自己的网站做宣传For example, I have a directory with many files, and I want to process all of them, but only 4 at a time in parallel.这正是线程池所做的:创建作业,池一次并行运行4个。通过使用执行器,您可以使事情变得更简单,您只需将函…
For example, I have a directory with many files, and I want to process all of them, but only 4 at a time in parallel.
这正是线程池所做的:创建作业,池一次并行运行4个。通过使用执行器,您可以使事情变得更简单,您只需将函数(或其他可调用函数)交给它,它就会将结果的未来交还给您。你可以自己建造,但你不必这么做
stdlib的^{}模块是最简单的方法。(对于Python3.1和更早版本,请参见backport)事实上,one of the main examples非常接近您想要做的事情。但是让我们根据您的具体用例调整它:def process_all_files(d):
files = glob.glob(d + '/*')
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:
fs = [executor.submit(process_file, file) for file in files]
concurrent.futures.wait(fs)
如果你想process_file返回一些东西,那几乎同样简单:def process_all_files(d):
files = glob.glob(d + '/*')
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:
fs = [executor.submit(process_file, file) for file in files]
for f in concurrent.futures.as_completed(fs):
do_something(f.result())
如果你也想处理异常…好吧,看看这个例子;它只是一个try/except调用周围的result()。
*如果你想自己建造,也没那么难。到^{}的源代码写得很好,注释也很好,没有那么复杂,而且大多数硬的东西都与线程无关;到^{}的源代码甚至更简单。