July 2002
Intermediate to advanced
608 pages
15h 46m
English
Credit: David Perry
You want to run a time-consuming function in a separate thread while allowing the main thread to continue uninterrupted.
The Future class sometimes allows you to hide the
fact that you’re using threading while still taking
advantage of threading’s potential performance
advantages:
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 '<Future at '+hex(id(self))+':'+self._ _status+'>'
def _ _call_ _(self):
self._ _C.acquire( )
while self._ _done==0:
self._ _C.wait( )
self._ _C.release( )
# Deepcopy _ _result to prevent accidental tampering with it
result = copy.deepcopy(self._ _result)
return result
def isDone(self):
return self._ _done
def Wrapper(self, func, param):
# Run the actual function and housekeep around it
self._ _C.acquire( )
self._ _result = func(*param)
self._ _done=1
self._ _status=`self._ _result`
self._ _C.notify( )
self._ _C.release( )Although Python’s thread syntax is nicer than the syntax in many languages, it can still be a pain if all you want to do is run a time-consuming function in a separate thread while allowing ...
Read now
Unlock full access