ThreadFuture.py
上传用户:lswyart
上传日期:2008-06-12
资源大小:3441k
文件大小:1k
源码类别:

杀毒

开发平台:

Visual C++

  1. ## code from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/84317
  2. from threading import *
  3. import copy
  4. class Future:
  5.     def __init__(self,func,*param):
  6.         # Constructor
  7.         self.__done=0
  8.         self.__result=None
  9.         self.__status='working'
  10.         self.__C=Condition()   # Notify on this Condition when result is ready
  11.         # Run the actual function in a separate thread
  12.         self.__T=Thread(target=self.Wrapper,args=(func,param))
  13.         self.__T.setName("FutureThread")
  14.         self.__T.start()
  15.     def __repr__(self):
  16.         return '<Future at '+hex(id(self))+':'+self.__status+'>'
  17.     def __call__(self):
  18.         self.__C.acquire()
  19.         while self.__done==0:
  20.             self.__C.wait()
  21.         self.__C.release()
  22.         # We deepcopy __result to prevent accidental tampering with it.
  23.         a=copy.deepcopy(self.__result)
  24.         return a
  25.     def Wrapper(self, func, param):
  26.         # Run the actual function, and let us housekeep around it
  27.         self.__C.acquire()
  28.         try:
  29.             self.__result=func(*param)
  30.         except:
  31.             self.__result="Exception raised within Future"
  32.         self.__done=1
  33.         self.__status=`self.__result`
  34.         self.__C.notify()
  35.         self.__C.release()