Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'

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, ())
like image 985
mikal94305 Avatar asked Jan 30 '26 21:01

mikal94305


2 Answers

If you are only trying to perform a small number of tasks, it may be better to use Process for reasons described here.

This site provides an excellent tutorial on use of Process() which i have found helpful. Here is an example from the tutorial using your 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()
like image 57
asheets Avatar answered Feb 01 '26 10:02

asheets


If you have no arguments to pass in, you don't have to use map. You can simply use multiprocessing.Pool.apply instead:

import multiprocessing


def function():
    for i in range(10):
        print(i)

if __name__ == '__main__':
    p = multiprocessing.Pool(5)
    p.apply(function)
like image 37
Christian Dean Avatar answered Feb 01 '26 10:02

Christian Dean



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!