threading

Dominic nomail at nospam.no
Tue Jun 29 22:51:43 CEST 2004


I would also favour a queue-based
solution.

This is something I have done
some time ago - for fun.
Maybe this old experimental
code snippet helps you somehow ;-)

Ciao,
  Dominic

from __future__ import generators
from thread import start_new
from md5 import md5
from time import sleep
from Queue import Queue

def heavy_task(str):
     print 'start heavy_task'
     sleep(1)
     print 'done'
     return md5(str).hexdigest()

def handle1():
     while 1:
         s = raw_input()
         a = Async(heavy_task)
         yield a(s)
         result = "Result is " + str(a.get_result())
         yield result

def main_loop():
     start_new(do_task,())
     context = handle1()
     while 1:
         async = context.next()
         ready_task.put(async.get_task())
         for i in range(10):
             print i,
             sleep(.5)
         async.set_result(done_task.get())
         print context.next()

#######################################################


ready_task = Queue()
done_task = Queue()

def do_task():
     while 1:
         func, args, kargs = ready_task.get()
         result = func(*args,**kargs)
         done_task.put(result)

class Async(object):
     result = None
     def __init__(self, obj):
         self.obj = obj
         return self
     def __call__(self, *args, **kargs):
         self.args = args
         self.kargs = kargs
         return self
     def get_result(self):
         return self.result
     def get_task(self):
         return (self.obj,self.args,self.kargs)
     def set_result(self, *args):
         self.result = args

main_loop()



More information about the Python-list mailing list