python两个循环同时运行,如何同时运行两个Python循环?

我发现在多重处理中使用池子模块非常适合在Python脚本中同时运行多个进程。

仔细查看示例#启动多个异步计算

可能使用更多进程

。一旦理解了这些行的功能, 我构建的下一个示例就有意义了。

import numpy as np

from multiprocessing import Pool

def desired_function(option, processes, data, etc...):

# your code will go here. option allows you to make choices within your script

# to execute desired sections of code for each pool or subprocess.

return result_array # "for example"

result_array = np.zeros("some shape") # This is normally populated by 1 loop, lets try 4.

processes = 4

pool = Pool(processes=processes)

args = (processes, data, etc...) # Arguments to be passed into desired function.

multiple_results = []

for i in range(processes): # Executes each pool w/ option (1-4 in this case).

multiple_results.append(pool.apply_async(param_process, (i+1,)+args)) # Syncs each.

results = np.array(res.get() for res in multiple_results) # Retrieves results after

# every pool is finished!

for i in range(processes):

result_array = result_array + results[i] # Combines all datasets!

这段代码基本上是运行给定数量的进程所需的功能。您将需要仔细确保您的函数可以区分每个进程(这就是我添加option变量的原因。)而且, 它不必是最后一个填充的数组, 但是对于我的示例, 这就是我的用法。希望这可以使它更容易或帮助您更好地理解Python中的多处理功能!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值