Книга: Learning Concurrency in Python
Назад: Apply
Дальше: Map


In situations where we need parallel execution of our tasks, this is the function we'll need to use in order to submit tasks to our pool.

In this example, we are going to use a for loop to submit four tasks to our processing pool as with our newly discovered apply_async. We keep track of these tasks by appending them to a tasks array, and then iterate over this task array to wait for the results:

from multiprocessing import Pool
import time
import os

def myTask(n):
print("Task processed by Process {}".format(os.getpid()))
return n*2

def main():
with Pool(4) as p:
tasks = []

for i in range(4):
task = p.apply_async(func=myTask, args=(i,))

for task in tasks:
print("Result: {}".format(task.get()))

if __name__ == '__main__':

Upon execution of this, you should see that our four tasks are picked up by our process pool, and executed by four distinct processes. Because we call task.wait() in the same order that they are submitted to the tasks array, we then get an ordered output of the results printing out to our console:

$ python3.6 21_applyAsync.py
Task processed by Process 99323
Task processed by Process 99324
Task processed by Process 99322
Task processed by Process 99325
Result: 0
Result: 2
Result: 4
Result: 6
Назад: Apply
Дальше: Map

Download missing dll from Download unarc.dll page. Fix your error now!
Interested in hardrock? How about KISS? They are on a tour this year all across Canada and USA. Visit KISS Tour Dates Omaha to know more about KISS concert dates in 2019.
Carrie Underwood is my favourite country singer. She is young, beautiful and charming female in her 30s. Her strong voice takes me away from all troubles of this world so I start enjoy my life and listen songs created by her mind. Now the singer is on a Cry Pretty 360 Tour started in May of 2019. The concerts scheduled for this year, up to the 31st of October. Tickets are available for all men and women with different income. If you love country music as mush as I, then you must visit at least one of her concert. All tour dates are available at the Carrie Underwood tour Pittsburgh. Visit the website and make yourself familiar with all powerful Carrie Underwood concerts in 2019!