/ Published in: Python
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
#!/usr/bin/python # -*- coding: utf-8 -*- from multiprocessing import Process, Queue #python2.6 def _pq(q,func,args,kargs):q.put(func(*args,**kargs)) class RunProc(object): def __init__(self,func, args=None,kargs=None): if args is None: args=() if kargs is None: kargs={} self.__q = Queue() self.__p = Process(target=_pq, args=(self.__q,func,args,kargs)) self.__p.start() def isRunning(self): return self.__p.is_alive() def get(self): if not hasattr(self,"_ret"): self.__p.join() self._ret=self.__q.get() return self._ret def kill(self): if self.isRunning(): self.__p.terminate() #~ import thread #~ class RunProc(object): #~ def __init__(self,func, args=None,kargs=None): #~ if args is None: args=() #~ if kargs is None: kargs={} #~ def _pq(self,func,args,kargs): #~ self.__lock.acquire() #~ self.__ret = func(*args,**kargs) #~ self.__lock.release() #~ self.__lock=thread.allocate_lock() #~ thread.start_new_thread(_pq,(self,func,args,kargs)) #~ while not self.isRunning(): pass #~ def isRunning(self): #~ return self.__lock and self.__lock.locked() #~ def get(self): #~ if self.__lock: #~ self.__lock.acquire() #~ self.__lock=None #~ return self.__ret #~ def kill(self): #~ pass def work(s,n,cb=None): import time time.sleep(s) l=range(n) if cb: cb(l) return l def mycb(l): print "***cb:",l if __name__ == '__main__': p2=RunProc( work, (2,6) ) assert p2.isRunning() v1=p2.get() assert not p2.isRunning() v2=p2.get() assert v1==v2 assert not p2.isRunning() p1=RunProc( work, (3,13),{"cb":mycb} ) p2=RunProc( work, (2,6) ) print p1.isRunning() print p2.isRunning() print p1.get() print p2.get()