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)
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。