内联回调函数
from queue import Queue
from functools import wraps

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

class Async:
	def __init__(self, func, args):
		self.func = func
		self.args = args
		
def inlined_async(func):
	@wraps(func)
	def wrapper(*args):
		f = func(*args)
		result_queue = Queue()
		result_queue.put(None)
		while True:
			result = result_queue.get()
			try:
				a = f.send(result)
				apply_async(a.func, a.args, callback=result_queue.put)
			except StopIteration:
				break
	return wrapper
	
def add(x, y):
	return x + y
	
@inlined_async
def test():
	r = yield Async(add, (2, 3))
	print(r)
	r = yield Async(add, ('hello', 'world!'))
	print(r)
	for n in range(10):
		r = yield Async(add, (n, n))
		print(r)
	print('Goodbye!')
	
test()
运行结果如下:
阅读更多
文章标签: python内联回调函数
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

内联回调函数

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭