Advertisement
Dapid

Untitled

May 8th, 2012
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.34 KB | None | 0 0
  1. '''
  2. Created on 23/04/2012
  3.  
  4. @author: Davidmh
  5. '''
  6. from __future__ import division
  7. from multiprocessing import Queue, Process, Pool
  8. import time
  9. import random
  10.  
  11. pars=[1,2]
  12. ncpu=2
  13.  
  14.  
  15. def calculate(par):
  16.     time.sleep(0.5*random.random()+0.5)
  17.     res=2*par
  18.     print par,',',res
  19.     q.put([par,res])
  20.     print '---'
  21.  
  22.  
  23.  
  24. def saving(q, savefile):
  25.     print '==Saving=='
  26.     while True:
  27.         try:
  28.             item=q.get(False)
  29.             print item
  30.         except :
  31.             print '%'
  32.             time.sleep(0.5)
  33.             continue
  34.  
  35.         savefile.write(item[0])
  36.         savefile.write(',')
  37.         savefile.write(item[1])
  38.         savefile.write('\r\n')
  39.  
  40.  
  41.  
  42. if __name__=="__main__":
  43.     print 'Started!'
  44.    
  45.     q=Queue()
  46.    
  47.     with open('test_par.txt', 'w', buffering=0) as savefile:
  48.         savefile.write('This is the test file\r\n')
  49.         print 'Standard map:'
  50.         map(calculate, pars)
  51.         print
  52.        
  53.         print 'Parallel map'
  54.         pool = Pool(processes=min(ncpu, len(pars)))
  55.         pool.map_async(calculate, pars, chunksize=1)
  56.         pool.close()
  57.  
  58.         k=Process(target=saving, args=(q,savefile,))
  59.         k.start()
  60.         pool.join()
  61.         print q.qsize()
  62.         q.close()
  63.         q.join_thread()
  64.        
  65.         k.terminate()
  66.         pool.terminate()
  67.     print 'End!'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement