How do I run a single function over a loop parallely? Python 2.7.12
<p>I'm trying to parallelize a program which uses a single function in a for loop which updates a global list/variable parallely. How do I go about this and how can I pass values to the function?</p>

<p>The sample code looks like this,</p>

<pre><code>#python 2.7.12
import random
sum=0

#sample function to take a random integer between 0 to i and add it to global variable sum
def hello(i):
    print "Thread Id :",i   #instead of i it should be the threadID
    sum=sum+random.randrange(0,i)

#main function  
i=1
for i in range(10): 
    hello(i)        #how to parallelize this function over a loop?
</code></pre>

<p>Edit 1 :
Tried using the Process from multiprocessing but don't know how to pass values to the functions and how to run it parallely over a loop.</p>

<pre><code>from multiprocessing import Process
sum=0 

def Hello(): 
   print 'hello: starting' 
   sum=sum+i    #Don't know how to pass values here 
   print 'hello: finishing' 

if name == 'main': 
   p1 = Process(target=func1) 
   p1.start() 
   p1.join()
   print sum
</code></pre>

<p>Pass the parameters as a tuple to the args kwarg of the Process function: Here is the example from the docs:</p>

<pre><code>if __name__ == '__main__':
    p = Process(target=f, args=('bob',))
    p.start()
    p.join()
</code></pre>

<p><a href="https://docs.python.org/2/library/multiprocessing.html" rel="nofollow">https://docs.python.org/2/library/multiprocessing.html</a></p>

<p>Also what John Gordon said in his comment is true too. You will need to have the master process (which will be running the loop) handle the summing. What you are basically trying to do is a simple map/reduce job. </p>

<p>The map part is your hello function and the reduce is the sum. There are lots of examples of doing map/reduce jobs in python.</p>

<p>Look at using a Pipe or Shared Memory for handling the sum, both are detailed in the multiprocessing docs mentioned above.</p>

python parallel-processing