‘‘‘协程无切换消耗实现了并发,并发:并非线程切,而是线程执行的任务的切换,如果直接切换任务,也是并发缺点:不能利用多核协程是重点,实现多并发,封装了很多好模块,后期应用‘‘‘ 协程基本实现
import time def consumer(): r = ‘‘ while True: n = yield r print(‘[CONSUMER]<<Consuming %s...‘ %n) time.sleep(1) r = ‘200 OK‘ def produce(c): next(c) n = 0 while n < 5: n = n + 1 print(‘[PRODUCER]>>Producing %s...‘ %n) cr = c.send(n) print(‘[PRODUCER]>>Consumer return: %s‘ % cr) if __name__ == ‘__main__‘: c = consumer() produce(c)
‘‘‘greenlet不常用,只能切任务,但是对IO密集型任务不能节省时间‘‘‘
from greenlet import greenlet def test1(): print(12) gr2.switch() print(34) gr2.switch() def test2(): print(56) gr1.switch() print(78) gr1 = greenlet(test1) gr2 = greenlet(test2) gr1.switch()
‘‘‘gevent第三方库当一个greenlet遇到IO操作时,比如访问网络,就自动切换到其他的greenlet,等到IO操作完成,再在适当的时候切换回来继续执行‘‘‘
import requests,gevent,time from gevent import monkey monkey.patch_all() # 由于切换是在IO操作时自动完成,所以gevent需要修改Python自带的一些标准库,这一过程在启动时通过monkey patch完成 def foo(url): response=requests.get(url) response_str=response.text print("GET data %s"%len(response_str),url) s=time.time() gevent.joinall([gevent.spawn(foo,"https://itk.org/"), gevent.spawn(foo,"https://www.github.com/")]) # gevent.spawn(foo, "https://zhihu.com/")]) print(time.time()-s)
时间: 2024-10-10 22:01:05