2010-08-28

Delegate in Python(Python Asynchronous Programming)

Views: 11862 | Add Comments

The .NET Framework enables you to call any method asynchonously, by the two methods BeginInvoke and EndInvoke. The BeginInvoke method is used to register a function execution to Delegate(background threads), it quickly returns, so you can execute other codes after. In later time, you can use EndInvoke to get the return of the execution of that registered function, or you may had register a Callback function in the mean time you register that function, so this Callback will be automatically executed.

The structure of source code can be demonstrate in this steps:

  1. handle = BeginInvoke(my_function)
  2. do other work
  3. result = handle.EndInvoke()
  4. deal with result

Or in callback way:

  1. handle = BeginInvoke(my_function, callback)
  2. do other work

Python does not support Asynchronous, so I made a Delegate class, you can do Asynchronous Programming in the same way like .NET Framework does:

#encoding=UTF-8
import time, random
import sys
from delegate import *

def proc(a):
    time.sleep(random.random())
    return str(a)

def proc_callback(handle, args=None):
    try:
        ret = d.end(handle)
        log.debug('proc return: ' + repr(ret))
    except Exception,e:
        log.warn('end throw Exception: ' + str(e))
        return

d = Delegate()
d.init(2) # number of workers

n = 0
while True:
    n += 1
    log.debug("Press 'q' to quit, Enter to continue.")
    line = sys.stdin.readline().strip()
    if line == 'q':
        break
    data = str(n)
    handle = d.begin(proc, data, proc_callback, 'test')
    log.debug('register ' + data)

d.free()

Download source code: pap.zip API doc

Posted by ideawu at 2010-08-28 17:00:29

Leave a Comment