Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- list_sum = sum(my_list)
- core1_sum = sum(my_list[0:500000]) #goes to core 1
- core2_sum = sum(my_list[500001:1000000]) #goes to core 2
- all_core_sum = core1_sum + core2_sum #core 3 does final computation
- from multiprocessing import Process, Queue
- def do_sum(q,l):
- q.put(sum(l))
- def main():
- my_list = range(1000000)
- q = Queue()
- p1 = Process(target=do_sum, args=(q,my_list[:500000]))
- p2 = Process(target=do_sum, args=(q,my_list[500000:]))
- p1.start()
- p2.start()
- r1 = q.get()
- r2 = q.get()
- print r1+r2
- if __name__=='__main__':
- main()
- from multiprocessing import Process, Queue
- thelist = range(1000*1000)
- def f(q, sublist):
- q.put(sum(sublist))
- def main():
- start = 0
- chunk = 500*1000
- queue = Queue()
- NP = 0
- subprocesses = []
- while start < len(thelist):
- p = Process(target=f, args=(queue, thelist[start:start+chunk]))
- NP += 1
- print 'delegated %s:%s to subprocess %s' % (start, start+chunk, NP)
- p.start()
- start += chunk
- subprocesses.append(p)
- total = 0
- for i in range(NP):
- total += queue.get()
- print "total is", total, '=', sum(thelist)
- while subprocesses:
- subprocesses.pop().join()
- if __name__ == '__main__':
- main()
- $ python2.6 mup.py
- delegated 0:500000 to subprocess 1
- delegated 500000:1000000 to subprocess 2
- total is 499999500000 = 499999500000
Add Comment
Please, Sign In to add comment