def apply_async(func, args, , callback): # Compute the result result = func(args)
# Invoke the callback with the result
callback(result)
def print_result(result): ... print('Got:', result) ... def add(x, y): ... return x + y ... apply_async(add, (2, 3), callback=print_result) Got: 5 apply_async(add, ('hello', 'world'), callback=print_result) Got: helloworld
还有另外一个更高级的方法,可以使用协程来完成同样的事情:
def make_handler(): sequence = 0 while True: result = yield sequence += 1 print('[{}] Got: {}'.format(sequence, result)) 对于协程,你需要使用它的 send() 方法作为回调函数,如下所示:
handler = make_handler() next(handler) # Advance to the yield apply_async(add, (2, 3), callback=handler.send) [1] Got: 5 apply_async(add, ('hello', 'world'), callback=handler.send) [2] Got: helloworld