python-3.x - 在函数中使用多处理
问题描述
我想从下面获取工作代码并将其放入一个函数中。
import multiprocessing as mp
def parameters(x,n):
for i in x:
yield (i,n)
def power(a):
x, n = a
return x**n
if __name__ == '__main__':
p = [i for i in range(1000)]
p = parameters(p,2)
agents = 4
chunk = 10
with mp.Pool(processes = agents) as pool:
o = pool.map(power,p,chunksize = chunk)
print(o)
这样我就可以随时调用它。我试着做这样的事情:
import multiprocessing as mp
def parameters(x,n):
for i in x:
yield (i,n)
def power(a):
x, n = a
return x**n
def calculate(s,n):
p = [i for i in range(s)]
p = parameters(p,n)
agents = 4
chunk = 10
with mp.Pool(processes = agents) as pool:
o = pool.map(power,p,chunksize = chunk)
return o
print(calculate(1000,2))
但是,这根本不起作用,它告诉我另一个进程在一个进程结束之前已经开始。但是上面的代码确实有效。有没有办法将此代码正确地放入函数中?如果不使用此设置,那么使用什么设置?
解决方案
确保保护只应在主进程中运行的代码if __name__ == '__main__':
。此代码有效:
import multiprocessing as mp
def parameters(x,n):
for i in x:
yield (i,n)
def power(a):
x, n = a
return x**n
def calculate(s,n):
p = [i for i in range(s)]
p = parameters(p,n)
agents = 4
chunk = 10
with mp.Pool(processes = agents) as pool:
o = pool.map(power,p,chunksize = chunk)
return o
if __name__ == '__main__':
print(calculate(1000,2))
如果没有if
,则会引发以下错误:
RuntimeError:
An attempt has been made to start a new process before the
current process has finished its bootstrapping phase.
This probably means that you are not using fork to start your
child processes and you have forgotten to use the proper idiom
in the main module:
if __name__ == '__main__':
freeze_support()
...
The "freeze_support()" line can be omitted if the program
is not going to be frozen to produce an executable.
推荐阅读
- swift - Swift:我在 Firebase 存储中的文件不会被删除
- python - 让 Pycharm 知道类
- android - 呼叫机器人 - 如何?
- excel - VBA 覆盖或追加到新工作簿
- richtextbox - 石板与散文镜
- javascript - 使用 Node JS 到 MySQL 的 HTML 表单数据不起作用
- javascript - 在 mongodb 中保存当前日期
- laravel - laravel 5.7:使用唯一数据分页
- git - How to remove a folder from a repository in github?
- java - 在 Java 代码 eclipse 中使用 cTakes 和 UIMA