简体   繁体   中英

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, ())

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)

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM