python下的协程:
1
#
encoding=utf-8
2
"""
3
协程----微小的进程
4
yield生成器-----生成一个可迭代对象比如list, tuple,dir
5
1、包含yield的函数,则是一个可迭代对象(list, tuple等)
6
每次运行到yield即结束,并保留现场
7
2、生产者、消费者行为;
8
9
3、无需立即执行,需要时才执行
10
"""
11
12 a = [1, 2, 3, 4]
13for i in a:
14print i
1516def test():
17 i = 0
18 a = 4
19while i < a:
20"""21 0
22 1
23 2
24 3
25"""26 x = yield i
27 i += 1
2829 t = test()
30print t #<generator object test at 0x0000000002541798>31print t.next() #生成器的next()32print t.next() #生成器的next()33print t.next() #生成器的next()34print t.next() #生成器的next()35#print t.next() #StopIteration3637print type(range(0, 5)) #<type ‘list‘>38print type(xrange(0, 5)) #<type ‘xrange‘>3940def test2():
41 x = yield"first, and return"42print"first %s"%x
43 x = yield"second and return%s"%x
44print"second %s"%x
45 x = yield46print x #None,没有send474849 t = test2()
50print t.next()
51print t.send("try again") #使用send()则x的值为send的参数,未使用send则x为空52print t.send("the second args")
5354# 1 1 2 3 5 8 1355print"=================="56def test3(num):
57if num == 1:
58yield num
59 i = 1
60 b = 1
61while i < num:
62 x = yield i
6364 i = b + i
656667for i in test3(13):
68print i
697071"""72求100000之后的100个质数, 使用yield
73"""74def is_p(t_int):
75if t_int > 1:
76for i in xrange(2, t_int):
77if t_int%i == 0:
78return False
79return True
80else:
81return False
8283def get_primes():
84 i = 10000
85while True:
86if is_p(i):
87#x = yield i88yield i
89 i +=1
90 i += 1
9192 t = get_primes()
93for i in xrange(0, 100):
94print t.next()
原文:http://www.cnblogs.com/chris-cp/p/4660145.html
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!