我正在尝试使用Python进行多处理器编程.Fibonacci例如,采用分治算法.程序流程的执行将像树一样分支并并行执行.换句话说,我们有一个嵌套并行性的例子.
从Java开始,我使用线程池模式来管理资源,因为程序可以非常快速地扩展并创建太多短期线程.可以通过实例化单个静态(共享)线程池 ExecutorService.
我希望Pool也一样,但看起来Pool对象不是全局共享的.例如,使用共享池multiprocessing.Manager.Namespace()将导致错误.
池对象不能在进程之间传递或被pickle
我有一个由两部分组成的问题:
from concurrent.futures import ThreadPoolExecutor
def fibonacci(n):
if n < 2:
return n
a = pool.submit(fibonacci, n - 1)
b = pool.submit(fibonacci, n - 2)
return a.result() + b.result()
def main():
global pool
N = int(10)
with ThreadPoolExecutor(2**N) as pool:
print(fibonacci(N))
main()
Run Code Online (Sandbox Code Playgroud)
Java的
public class FibTask implements Callable<Integer> {
public static ExecutorService pool = Executors.newCachedThreadPool();
int …Run Code Online (Sandbox Code Playgroud) 我有一个df交易者交易数据集。我有 2 个级别的 for 循环,如下所示:
smartTrader =[]
for asset in range(len(Assets)):
df = df[df['Assets'] == asset]
# I have some more calculations here
for trader in range(len(df['TraderID'])):
# I have some calculations here, If trader is successful, I add his ID
# to the list as follows
smartTrader.append(df['TraderID'][trader])
# some more calculations here which are related to the first for loop.
Run Code Online (Sandbox Code Playgroud)
我想并行化 中每个资产的计算Assets,并且我还想并行化每个资产的每个交易者的计算。完成所有这些计算后,我想根据smartTrader.
这是我第一次尝试并行处理,所以请耐心等待,非常感谢您的帮助。