[英]How do you use Python Multiprocessing for a function with zero positional arguments?
Here is an example: 这是一个例子:
import multiprocessing
def function():
for i in range(10):
print(i)
if __name__ == '__main__':
p = multiprocessing.Pool(5)
p.map(function, )
yields the error: TypeError: map() missing 1 required positional argument: 'iterable'
产生错误:
TypeError: map() missing 1 required positional argument: 'iterable'
The function does not need any input, so I wish to not artificially force it to. 该功能不需要任何输入,因此我希望不要人为地强迫它。 Or does multiprocessing need some iterable?
还是多处理需要一些迭代?
The following code returns / prints nothing. 以下代码不返回/不输出任何内容。 Why?
为什么?
import multiprocessing
def function():
for i in range(10):
print(i)
if __name__ == '__main__':
p = multiprocessing.Pool(5)
p.map(function, ())
If you have no arguments to pass in, you don't have to use map
. 如果没有要传递的参数,则不必使用
map
。 You can simply use multiprocessing.Pool.apply
instead: 您可以简单地使用
multiprocessing.Pool.apply
代替:
import multiprocessing
def function():
for i in range(10):
print(i)
if __name__ == '__main__':
p = multiprocessing.Pool(5)
p.apply(function)
If you are only trying to perform a small number of tasks, it may be better to use Process
for reasons described here . 如果您仅尝试执行少量任务,则出于此处所述的原因,最好使用
Process
。
This site provides an excellent tutorial on use of Process()
which i have found helpful. 该站点提供了有关使用
Process()
的出色教程,我发现它很有帮助。 Here is an example from the tutorial using your function()
: 这是使用您的
function()
的教程示例:
import multiprocessing
def function():
for i in range(10):
print(i)
if __name__ == '__main__':
jobs = []
for i in range(5):
p = multiprocessing.Process(target=function)
jobs.append(p)
p.start()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.