Advertisement
Guest User

multiproc.py

a guest
Nov 3rd, 2011
243
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.47 KB | None | 0 0
  1. #!/usr/bin/env python2
  2.  
  3. from multiprocessing import Process, Queue
  4. from Queue import Empty
  5. import numpy as np
  6.  
  7. START = 'START'
  8. FINAL = 'FINAL'
  9. STEPS = 'STEPS'
  10. SIZE  = 'SIZE'
  11. P_IMMUNE = 'P_IMMUNE'
  12.  
  13. def run_sim (in_, out_):
  14.     try:
  15.         while True:
  16.             sim = in_.get(False) # get simulation from input
  17.             start = np.zeros((sim[SIZE], sim[SIZE]))
  18.             final = np.array(start) # Clone start
  19.             steps = 0
  20.             # Perform the rest of the simulation
  21.  
  22.             # Store the results in the dict
  23.             sim[START] = start
  24.             sim[FINAL] = final
  25.             sim[STEPS] = steps
  26.             out_.put(sim) # put result in output
  27.     except Empty:
  28.         pass # I expect to get this when the queue is empty. That's OK.
  29.  
  30.  
  31. cores = 2 # NB. Make sure this is not higher than the number of cores on your
  32.           # computer!
  33. runs = 10
  34. n = 10
  35. p = .5683645 # Number pulled out of my head at quasi-random
  36.  
  37. inbox = Queue()
  38. outbox = Queue()
  39.  
  40. for i in xrange(runs):
  41.     inbox.put({
  42.         SIZE: n,
  43.         P_IMMUNE: p
  44.     })
  45.  
  46. workers = []
  47. for i in xrange(cores):
  48.     worker = Process(target=run_sim, args=(inbox,outbox))
  49.     worker.start()
  50.     workers.append(worker)
  51.  
  52. results = []
  53. for i in xrange(runs):
  54.     results.append(outbox.get()) # get results from the workers
  55.  
  56. # at this point all results collected workers are stopped.
  57.  
  58. for worker in workers:
  59.     worker.join() # 'rightsize' workers
  60.  
  61. print results
  62.  
  63.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement