How to sum Threads in python
Question: I need help on how i can sum all the threads.to get sum of thread one to three
all together..The parallel program should use all processors in host computer

    
    
    import threading
    import time
    from datetime import datetime
    
    start_time = datetime.now()   
    def sum_number():   
    
    summ = 100
    for num in range (1, 100):
      summ = summ + num
      num -= 1
     print ("SUM IS", summ)
    
    
    def sum_number1():  
    
      summr = 200
      for num in range (101,200):
        summr = summr + num
        num -= 1
        print ("SUM IS", summr)
    
    
    
     def sum_number2():
      summy = 300
      for num in range (201, 300):
        summy = summy + num
        num -= 1
        print ("SUM IS", summy)
    
    
    #take time t2
    #end_time =datetime.now()
    #print t2 -t1
    
    #print('Time taken : {}'. format(end_time-start_time))
    if __name__=="__main__":
    
      #sum_number()
      #sum_number1()
      #sum_number2()
      #sum_number3()
    
      t1=threading.Thread(target=sum_number)
    
      t1.start()
      time.sleep(5)
    
      t2=threading.Thread(target=sum_number1)
    
      t2.start()
      time.sleep(10)
    
      t3=threading.Thread(target=sum_number2)
    
      t3.start()
      time.sleep(15)
    
    
    
      #end_time =datetime.now()
    

I need help on how i can sum all the threads.to get sum of thread one to three
all together..The parallel program should use all processors in host computer


Answer: You can do

    
    
    import time
    import multiprocessing.dummy as mp # uses threads instead of full processes
    
    def sum_range(start_stop):
        start,stop=start_stop
        return sum(range(start,stop))
    
    if __name__=="__main__":
        start_time=time.perf_counter()
        with mp.Pool() as p:
            my_sums=p.map(sum_range,[(1,101),(101,201),(201,301)]) # sums from 1 to 300 (including 300)
            full_sum=sum(my_sums) 
        end_time=time.perf_counter()
        print("The sum is", full_sum)
        print("Calculating it took",end_time-start_time, "seconds." ) 
    

for using processes instead of threads use `import multiprocessing as mp`

In this case if you are after performance, doing the sum in a single
thread/process is much faster because you are summing so few numbers. Creating
Threads takes time and creating Processes takes much more time. (Normally
using threads does not increase computational performance with the standard
interpreter if you are not using special functions which release the "GIL")

