Skip to main content

Hi, I'm Mariano Guerra, below is my blog, if you want to learn more about me and what I do check a summary here: marianoguerra.github.io or find me on twitter @warianoguerra or mastodon @marianoguerra@vis.social

2^7 posts


import gobject
import thread

class Function( object ):
'''a class that represent a function that will run
on a thread and call a callback with the return value'''

def __init__( self, function, callback ):
self.function = function
self.callback = callback
self.queue = Queue.Queue( 0 )

def __call__( self, *args ):
'''when the object is called we start a thread
with the function and parameters and start the
check function that check every 0.2 seconds if
the thread has ended (there is something in the
queue), then call the callback with the result'''

thread.start_new_thread( self._function, args )
gobject.timeout_add( 200 , self.check )

def _function( self, *args ):
'''our function call the parameter function
with the args and put the return value in the
queue'''

self.queue.put( self.function( *args ) )

def check( self ):
'''check there is something in the queue
that means that self.function has ended
then call the callback with the result'''

try:
result = self.queue.get( True, 0.01 )
self.callback( result )
return False
except Queue.Empty:
return True

if __name__ == '__main__':
import time

def funcion(a,b):
time.sleep(5)
return a+b

def callback( suma ):
print suma

f = Function( funcion, callback )
f( 2,3 )
import gtk
gtk.main()


una clase que escribi que basicamente permite hacer que una clase se comporte como una funcion, con el adicional de que corre la funcion en un thread aparte y al terminar llama a la funcion callback pasandole el return como parametro.

util para funciones que demoran mucho para evitar bloquear otras cosas (como el refresco de la interfaz grafica)

si no contamos los comentarios esa clase debe tener 15 lineas, pero el resultado es que nos olvidamos de los threads :)

Comments

Comments powered by Disqus