Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiprocessing.Pool example

I'm trying to learn how to use multiprocessing, and found the following example.

I want to sum values as follows:

from multiprocessing import Pool from time import time  N = 10 K = 50 w = 0  def CostlyFunction(z):     r = 0     for k in xrange(1, K+2):         r += z ** (1 / k**1.5)     print r     w += r     return r  currtime = time()  po = Pool()  for i in xrange(N):     po.apply_async(CostlyFunction,(i,)) po.close() po.join()  print w print '2: parallel: time elapsed:', time() - currtime 

I can't get the sum of all r values.

like image 450
litd Avatar asked Dec 10 '10 22:12

litd


People also ask

What is a multiprocessing pool?

Functional Programming in Python In this lesson, you'll dive deeper into how you can use multiprocessing. Pool . It creates multiple Python processes in the background and spreads out your computations for you across multiple CPU cores so that they all happen in parallel without you needing to do anything.

What does multiprocessing process do?

multiprocessing is a package that supports spawning processes using an API similar to the threading module. The multiprocessing package offers both local and remote concurrency, effectively side-stepping the Global Interpreter Lock by using subprocesses instead of threads.

What does pool map do?

The pool's map method chops the given iterable into a number of chunks which it submits to the process pool as separate tasks. The pool's map is a parallel equivalent of the built-in map method. The map blocks the main execution until all computations finish. The Pool can take the number of processes as a parameter.


1 Answers

If you're going to use apply_async like that, then you have to use some sort of shared memory. Also, you need to put the part that starts the multiprocessing so that it is only done when called by the initial script, not the pooled processes. Here's a way to do it with map.

from multiprocessing import Pool from time import time  K = 50 def CostlyFunction((z,)):     r = 0     for k in xrange(1, K+2):         r += z ** (1 / k**1.5)     return r  if __name__ == "__main__":     currtime = time()     N = 10     po = Pool()     res = po.map_async(CostlyFunction,((i,) for i in xrange(N)))     w = sum(res.get())     print w     print '2: parallel: time elapsed:', time() - currtime 
like image 176
Justin Peel Avatar answered Oct 02 '22 12:10

Justin Peel