通过生成器可以实现协程
协程
协程是一种并发运行机制,适用于I/O密集场景,有时候也称为微线程
协程就是利用生成器实现
协程应用举例
import os
# 装饰器,使生成器指向第一个yield
def coroutine(func):
def start(*args, **kwargs):
g = func(*args, **kwargs)
g.__next__()
return g
return start
@coroutine
def find_files(target):
while True:
topdir = yield
for path, dirname, filelist in os.walk(topdir):
for name in filelist:
if name.endswith(".py"):
print(name)
target.send(os.path.join(path, name))
@coroutine
def opener(target):
while True:
filename = yield
with open(filename,"r") as f:
for line in f.readlines():
target.send(line)
@coroutine
def grepline():
while True:
line = yield
print(line)
f_generate = find_files(opener(grepline()))
f_generate.send(".")
讨论区