Apply is to Pools as .submit() is to ThreadPoolExecutors. This is to say, they are just about the same in the sense that you use them to submit to individual tasks to our pools objects.
In this example, we are going to define a simple myTask function which will take in one parameter. This is the same myTask function that we'll use in all the subsequent examples for this section of the book.
We then go into our main function, which starts our Pool as a context manager, and simply prints out the result of each of these tasks:
from multiprocessing import Pool
import time
def myTask(n):
time.sleep(n/2)
return n*2
def main():
with Pool(4) as p:
print(p.apply(myTask, (4,)))
print(p.apply(myTask, (3,)))
print(p.apply(myTask, (2,)))
print(p.apply(myTask, (1,)))
if __name__ == '__main__':
main()
It should be each noted that the .apply() function blocks until the result is ready, so, it's not exactly ideal for doing work in parallel. If you wanted to perform work in parallel, then you should really be using the .apply() sister function, apply_async.