www.pudn.com > 10040637740.zip > ThreadFuture.py


## code from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/84317 
 
from threading import * 
import copy 
class Future: 
    def __init__(self,func,*param): 
        # Constructor 
        self.__done=0 
        self.__result=None 
        self.__status='working' 
 
        self.__C=Condition()   # Notify on this Condition when result is ready 
 
        # Run the actual function in a separate thread 
        self.__T=Thread(target=self.Wrapper,args=(func,param)) 
        self.__T.setName("FutureThread") 
        self.__T.start() 
 
    def __repr__(self): 
        return '' 
 
    def __call__(self): 
        self.__C.acquire() 
        while self.__done==0: 
            self.__C.wait() 
        self.__C.release() 
        # We deepcopy __result to prevent accidental tampering with it. 
        a=copy.deepcopy(self.__result) 
        return a 
 
    def Wrapper(self, func, param): 
        # Run the actual function, and let us housekeep around it 
        self.__C.acquire() 
        try: 
            self.__result=func(*param) 
        except: 
            self.__result="Exception raised within Future" 
        self.__done=1 
        self.__status=`self.__result` 
        self.__C.notify() 
        self.__C.release()