044协程
Posted Alos
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了044协程相关的知识,希望对你有一定的参考价值。
内容:协程 作用:实现高并发,提高效率
##################################################################
yield支持下的协程
协程是用户轻量级线程
好处:
1、没有线程切换
2、无需原子操作锁定及同步开销
3、高并发+高扩展+低成本:一个cpu支持上万的协程都没有问题。所以很适合高并发处理
缺点:
1、无法利用多核利用——通过多进程改进
2、一个阻塞,则全部都阻塞了
def consumer(name): print(\'start\') while True: new_baozi = yield print("[%s]is eating baozi %s" % (name,new_baozi)) def producer(): r = con.__next__() r = con2.__next__() n = 0 while n < 5: n += 1 con.send(n) con2.send(n) print("\\033[32;lm[producer]\\033[0m is making baozi %s" % n) if __name__ == \'__main__\': con = consumer(\'c1\') con2 = consumer(\'c2\') p = producer()
执行结果:
start
start
[c1] is eating baozi 1
[c2] is eating baozi 1
[c1] is eating baozi 2
[c2] is eating baozi 2
[c1] is eating baozi 3
[c2] is eating baozi 3
[c1] is eating baozi 4
[c2] is eating baozi 4
[c1] is eating baozi 5
[c2] is eating baozi 5
############################################################
gevent下的协程
1、安装
搜索gevent,然后安装
#####greenlet
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() # 开始执行
执行结果:
12
56
34
78
######gevent
import gevent def foo(): print(\'running in foo\') gevent.sleep() print(\'Explicit context switch to foo again\') def bar(): print(\'Explicit context to bar\') gevent.sleep() print(\'Implicit context switch back to bar\') gevent.joinall([ gevent.spawn(foo), gevent.spawn(foo) ])
执行结果:
running in foo
Explicit context to bar
Explicit context switch to foo again
Implicit context switch back to bar
爬网站,可以明显看出串行和并发的效果
from gevent import monkey monkey.patch_all() import gevent from urllib.request import urlopen def f(url): print(\'get:%s\'%url) resp = urlopen(url) data = resp.read() print(\'%dbytesreceviedfrom%s.\' % (len(data),url)) with open(\'xx.html\',\'wb\') as f: f.write(data) gevent.joinall([ gevent.spawn(f,\'https://www.baidu.com\'), #gevent.spawn(f,\'192.168.10.142\'), #gevent.spawn(f,\'192.168.10.142:8080\') ])
以上是关于044协程的主要内容,如果未能解决你的问题,请参考以下文章
2022团体程序设计天梯赛GPLT2022,L1~L2部分(PTA,L1-081~L1-088,L2-041~L2-044)题解代码&复盘