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] 13 for i in a: 14 print i 15 16 def test(): 17 i = 0 18 a = 4 19 while i < a: 20 """ 21 0 22 1 23 2 24 3 25 """ 26 x = yield i 27 i += 1 28 29 t = test() 30 print t #<generator object test at 0x0000000002541798> 31 print t.next() #生成器的next() 32 print t.next() #生成器的next() 33 print t.next() #生成器的next() 34 print t.next() #生成器的next() 35 #print t.next() #StopIteration 36 37 print type(range(0, 5)) #<type 'list'> 38 print type(xrange(0, 5)) #<type 'xrange'> 39 40 def test2(): 41 x = yield "first, and return" 42 print "first %s"%x 43 x = yield "second and return%s"%x 44 print "second %s"%x 45 x = yield 46 print x #None,没有send 47 48 49 t = test2() 50 print t.next() 51 print t.send("try again") #使用send()则x的值为send的参数,未使用send则x为空 52 print t.send("the second args") 53 54 # 1 1 2 3 5 8 13 55 print "==================" 56 def test3(num): 57 if num == 1: 58 yield num 59 i = 1 60 b = 1 61 while i < num: 62 x = yield i 63 64 i = b + i 65 66 67 for i in test3(13): 68 print i 69 70 71 """ 72 求100000之后的100个质数, 使用yield 73 """ 74 def is_p(t_int): 75 if t_int > 1: 76 for i in xrange(2, t_int): 77 if t_int%i == 0: 78 return False 79 return True 80 else: 81 return False 82 83 def get_primes(): 84 i = 10000 85 while True: 86 if is_p(i): 87 #x = yield i 88 yield i 89 i +=1 90 i += 1 91 92 t = get_primes() 93 for i in xrange(0, 100): 94 print t.next()