Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036
00037
00038
00039
00040
00041
00042 """
00043 Provides classes for quick threading of object methods
00044
00045 In your class, just add this line to the __init__:
00046 self.post=Post(self)
00047
00048 You can now call any object methods with object.post.method(args)
00049 The Thread object is returned.
00050
00051 """
00052
00053
00054 from threading import Thread
00055
00056 class PostThread(Thread):
00057 """ Object that manages the threaded execution of a given function """
00058
00059 def __init__(self,func):
00060 """ Creates the thread object with the method to be called """
00061 Thread.__init__(self,)
00062 self.func=func
00063 self.isRunning=True
00064 self.result=None
00065 self.daemon=True
00066
00067 def execute(self,*args,**kwargs):
00068 """ Store the method call arguments and start the thread, returns the thread object to the caller """
00069 self.args=args
00070 self.kwargs=kwargs
00071 self.start()
00072 return self
00073
00074 def run(self):
00075 """ Thread execution, call the function with saved arguments, saves result and change flag at the end """
00076 self.result=self.func(*self.args,**self.kwargs)
00077 self.isRunning=False
00078
00079 def kill(self):
00080 if self.isAlive():
00081 self._Thread__stop()
00082
00083 class Post:
00084 """ Object that provides threaded calls to its parent object methods """
00085 def __init__(self,parent):
00086 self.parent=parent
00087
00088 def __getattr__(self,attr):
00089 """ Find the method asked for in parent object, encapsulate in a PostThread object and send back pointer to execution function"""
00090 try:
00091 func=getattr(self.parent,attr)
00092 post_thread=PostThread(func)
00093 return post_thread.execute
00094 except:
00095 raise Exception("ERROR: Post call on %s: method %s not found"%(str(self.parent),attr))
00096
00097
00098 if __name__=="__main__":
00099 class Dummy:
00100 def __init__(self):
00101 self.post=Post(self)
00102
00103 def do(self,param):
00104 import time
00105 print "Doing... param="+str(param)
00106 time.sleep(2)
00107 print "Done"
00108 return param
00109
00110
00111 dummy=Dummy()
00112 dummy.do("direct1")
00113 dummy.post.do("post1")
00114 dummy.post.do("post2")
00115 t3=dummy.post.do("post3")
00116 t3.join()
00117 print t3.result
00118 print "Finished"
00119