标签:splay one 方式 name next ade user ack 例子
10
-
import inspect def gen_func(): value = yield 1 # value = yield from #第一返回值给调用方, 第二调用方通过send方式返回值给gen return "lewen" #1. 用同步的方式编写异步的代码, 在适当的时候暂停函数并在适当的时候启动函数 gen = gen_func() print(inspect.getgeneratorstate(gen)) next(gen) print(inspect.getgeneratorstate(gen)) try: next(gen) except StopIteration: pass print(inspect.getgeneratorstate(gen))
-
11
-生成器实现协程例子
import socket def get_socket_data(): yield "lewen" def downloader(url): client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.setblocking(False) try: client.connect((host, 80)) # 阻塞不会消耗cpu except BlockingIOError as e: pass selector.register(self.client.fileno(), EVENT_WRITE, self.connected) source = yield from get_socket_data() data = source.decode("utf8") html_data = data.split("\r\n\r\n")[1] print(html_data) def download_html(html): html = yield from downloader() if __name__ == "__main__": # 协程的调度依然是 事件循环+协程模式 ,协程是单线程模式 pass
11
之前,装饰器coroutine + 生成器实现协程
现在,Python 有了原生的协程
标签:splay one 方式 name next ade user ack 例子
原文地址:https://www.cnblogs.com/wenyule/p/10322290.html