python3控制线程数量_如何限制Python中并发线程的数量?

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()。

*如果你想自己建造,也没那么难。到^{}的源代码写得很好,注释也很好,没有那么复杂,而且大多数硬的东西都与线程无关;到^{}的源代码甚至更简单。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值