這次看了一些關(guān)于協(xié)程(coroutine)的資料,這是python特有的,我會(huì)在這篇文字里面慢慢總結(jié)整理下來,估計(jì)會(huì)寫個(gè)1周多。
coroutine和generator的關(guān)系
generator用到了yield語法,而coroutine也是用到了yield語法,什么區(qū)別呢?大致是這樣的:
- generator是為iteration產(chǎn)生數(shù)據(jù)
- coroutine是消費(fèi)數(shù)據(jù)
- coroutine也可以產(chǎn)生值,但目的不是為了迭代
- 不要把2個(gè)概念混在一起,寫出讓大家摸不著頭腦的代碼
下面的代碼是generator,用來倒數(shù)迭代用
# countdown.py
#
# A simple generator function
def countdown(n):
print "Counting down from", n
while n > 0:
yield n
n -= 1
print "Done counting down"
# Example use
if __name__ == '__main__':
for i in countdown(5):
print i
輸出是
Counting down from 5
5
4
3
2
1
Done counting down
下面代碼是coroutine,用來消費(fèi)字符串,過濾出有用的行
# grep.py
#
# A very simple coroutine
def grep(pattern):
print "Looking for %s" % pattern
while True:
line = (yield)
if pattern in line:
print line,
# Example use
if __name__ == '__main__':
g = grep("python")
# g.send(None)
g.next()
g.send("Yeah, but no, but yeah, but no")
g.send("A series of tubes")
g.send("python generators rock!")
g.close()
輸出是
Looking for python
python generators rock!
千萬不要寫下面的代碼,又想消費(fèi),又想迭代,結(jié)果不知所云:
# bogus.py
#
# Bogus example of a generator that produces and receives values
def countdown(n):
print "Counting down from", n
while n >= 0:
newvalue = (yield n)
# If a new value got sent in, reset n with it
if newvalue is not None:
n = newvalue
else:
n -= 1
# The holy grail countdown
c = countdown(5)
for x in c:
print x
if x == 5:
c.send(3)
輸出是:
Counting down from 5
5
2
1
0