python协程
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 import gevent 4 from gevent import monkey;monkey.patch_all() 5 import requests 6 7 def f(url): 8 print('GET:%s'% url) 9 res = requests.get(url) 10 data= res.text 11 print(url,len(data)) 12 13 gevent.joinall( 14 [gevent.spawn(f,'http://www.baidu.com'), 15 gevent.spawn(f, 'http://www.qq.com'), 16 gevent.spawn(f,'http://www.58.com'), 17 gevent.spawn(f,'http://www.python.org'), 18 ] 19 ) 20 21 ''' 22 def foo(): 23 print('run foo.....') 24 gevent.sleep(2) 25 print('switch to foo.....') 26 27 def bar(): 28 print('run bar.....') 29 gevent.sleep(3) 30 print('switch to bar.....') 31 32 gevent.joinall([ 33 gevent.spawn(foo), 34 gevent.spawn(bar)]) 35 '''
生产者消费者模型
#!/usr/bin/env python # -*- coding:utf-8 -*- def consumer(): last = '' while True: receival = yield last if receival is not None: print('Consume %s' % receival) last = receival def producer(gen, n): gen.__next__() x = 0 while x < n: x += 1 print('Produce %s' % x) last = gen.send(x) gen.close() gen = consumer() producer(gen, 5)
消费者consumer()函数是一个生成器函数,每次执行到yield时即挂起,并返回上一次的结果给生产者。生产者producer()接收到生成器的返回,并生成一个新的值,通过send()方法发送给消费者。