异步,回调

def apply_async(func, args, callback):
    result = func(*args)
    callback(result)

def print_result(result):
    print "got:", result

def add(x,y):
    return x + y

apply_async(add, (2,3), callback=print_result)
apply_async(add, ("hello", "world"), callback=print_result)

在回调函数中携带外部信息

class ResultHandler:
    def __init__(self):
        self.sequence = 0
    def handler(self, result):
        self.sequence += 1
        print "[{}] got: {}".format(self.sequence, result)

r = ResultHandler()
apply_async(add, (2,3), callback=r.handler)
apply_async(add, ("hello", "world"), callback=r.handler)

用协程来实现

def make_handler():
    sequence = 0
    while True:
        result = yield
        sequence += 1
        print "[{}] got: {}".format(sequence, result)

handler = make_handler()
next(handler)
apply_async(add, (2,3), callback=handler.send)
apply_async(add, ("hello", "world"), callback=handler.send)

你可能感兴趣的:(异步,回调)