Guest User

Untitled

a guest
May 22nd, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. list_sum = sum(my_list)
  2.  
  3. core1_sum = sum(my_list[0:500000]) #goes to core 1
  4. core2_sum = sum(my_list[500001:1000000]) #goes to core 2
  5. all_core_sum = core1_sum + core2_sum #core 3 does final computation
  6.  
  7. from multiprocessing import Process, Queue
  8.  
  9. def do_sum(q,l):
  10. q.put(sum(l))
  11.  
  12. def main():
  13. my_list = range(1000000)
  14.  
  15. q = Queue()
  16.  
  17. p1 = Process(target=do_sum, args=(q,my_list[:500000]))
  18. p2 = Process(target=do_sum, args=(q,my_list[500000:]))
  19. p1.start()
  20. p2.start()
  21. r1 = q.get()
  22. r2 = q.get()
  23. print r1+r2
  24.  
  25. if __name__=='__main__':
  26. main()
  27.  
  28. from multiprocessing import Process, Queue
  29.  
  30. thelist = range(1000*1000)
  31.  
  32. def f(q, sublist):
  33. q.put(sum(sublist))
  34.  
  35. def main():
  36. start = 0
  37. chunk = 500*1000
  38. queue = Queue()
  39. NP = 0
  40. subprocesses = []
  41. while start < len(thelist):
  42. p = Process(target=f, args=(queue, thelist[start:start+chunk]))
  43. NP += 1
  44. print 'delegated %s:%s to subprocess %s' % (start, start+chunk, NP)
  45. p.start()
  46. start += chunk
  47. subprocesses.append(p)
  48. total = 0
  49. for i in range(NP):
  50. total += queue.get()
  51. print "total is", total, '=', sum(thelist)
  52. while subprocesses:
  53. subprocesses.pop().join()
  54.  
  55. if __name__ == '__main__':
  56. main()
  57.  
  58. $ python2.6 mup.py
  59. delegated 0:500000 to subprocess 1
  60. delegated 500000:1000000 to subprocess 2
  61. total is 499999500000 = 499999500000
Add Comment
Please, Sign In to add comment