Posted By

manatlan on 09/09/09


Tagged

python process thread


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

gartenstuhl


multiprocess thread


 / Published in: Python
 

  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3.  
  4. from multiprocessing import Process, Queue #python2.6
  5. def _pq(q,func,args,kargs):q.put(func(*args,**kargs))
  6. class RunProc(object):
  7. def __init__(self,func, args=None,kargs=None):
  8. if args is None: args=()
  9. if kargs is None: kargs={}
  10. self.__q = Queue()
  11. self.__p = Process(target=_pq, args=(self.__q,func,args,kargs))
  12. self.__p.start()
  13. def isRunning(self):
  14. return self.__p.is_alive()
  15. def get(self):
  16. if not hasattr(self,"_ret"):
  17. self.__p.join()
  18. self._ret=self.__q.get()
  19. return self._ret
  20. def kill(self):
  21. if self.isRunning():
  22. self.__p.terminate()
  23.  
  24.  
  25. #~ import thread
  26. #~ class RunProc(object):
  27. #~ def __init__(self,func, args=None,kargs=None):
  28. #~ if args is None: args=()
  29. #~ if kargs is None: kargs={}
  30. #~ def _pq(self,func,args,kargs):
  31. #~ self.__lock.acquire()
  32. #~ self.__ret = func(*args,**kargs)
  33. #~ self.__lock.release()
  34. #~ self.__lock=thread.allocate_lock()
  35. #~ thread.start_new_thread(_pq,(self,func,args,kargs))
  36. #~ while not self.isRunning(): pass
  37. #~ def isRunning(self):
  38. #~ return self.__lock and self.__lock.locked()
  39. #~ def get(self):
  40. #~ if self.__lock:
  41. #~ self.__lock.acquire()
  42. #~ self.__lock=None
  43. #~ return self.__ret
  44. #~ def kill(self):
  45. #~ pass
  46.  
  47.  
  48.  
  49.  
  50.  
  51. def work(s,n,cb=None):
  52. import time
  53. time.sleep(s)
  54. l=range(n)
  55. if cb: cb(l)
  56. return l
  57.  
  58.  
  59. def mycb(l):
  60. print "***cb:",l
  61.  
  62. if __name__ == '__main__':
  63. p2=RunProc( work, (2,6) )
  64. assert p2.isRunning()
  65. v1=p2.get()
  66. assert not p2.isRunning()
  67. v2=p2.get()
  68. assert v1==v2
  69. assert not p2.isRunning()
  70.  
  71. p1=RunProc( work, (3,13),{"cb":mycb} )
  72. p2=RunProc( work, (2,6) )
  73.  
  74. print p1.isRunning()
  75. print p2.isRunning()
  76.  
  77. print p1.get()
  78. print p2.get()

Report this snippet  

You need to login to post a comment.