gpt4 book ai didi

python - 多处理只运行函数而不是整个文件

转载 作者:行者123 更新时间:2023-12-04 08:40:30 25 4
gpt4 key购买 nike

如果我运行以下代码,它会在每次 pool.map 运行时运行 print("a") 。

from multiprocessing import Pool
from os import getpid

print("a")

def double(i):
print("I'm process", getpid())
return i * 2

if __name__ == '__main__':
with Pool() as pool:
result = pool.map(double, [1, 2, 3, 4, 5])
print(result)
通常这不是问题,但在我想要实现多处理的代码中,启动时间很长,这使得多处理需要很长时间才能获得结果,这抵消了使用多处理节省的时间。那么有没有办法让它只并行运行函数而不是整个文件?

最佳答案

您可以使用 multiprocessing.pool.ThreadPool在一个进程中运行该函数:

from multiprocessing.pool import ThreadPool
from os import getpid

print("a")

def double(i):
print("I'm process", getpid())
return i * 2

if __name__ == '__main__':
with ThreadPool() as pool:
result = pool.map(double, [1, 2, 3, 4, 5])
print(result)
打印(注意“乱码”输出):
a
I'm processI'm process I'm process 1
I'm process 1
I'm process1
1
1
[2, 4, 6, 8, 10]

关于python - 多处理只运行函数而不是整个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64591446/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com