python协程的作用
发布时间:2024-08-27 13:37:57

1、作用分析
(1)IO密集时,使用协程会提高效率。
(2)实现“IO切换+保存状态”欺骗操作系统,使操作系统错误地认为没有IO操作,并拥有CPU执行权,从而实现单线程下的并发性。
2、实例
importtime
#遇到IO切换(gevent)+保存状态
fromgeventimportmonkey#猴子补丁
monkey.patch_all()#监控所有任务是否有IO操作
fromgeventimportspawn#spawn(任务)
fromgeventimportjoinall
COUNT=10000000
start=time.clock()
defcountdown(n):
whilen>0:
n-=1
sp1=spawn(countdown,COUNT//2)
sp2=spawn(countdown,COUNT//2)
#sp1.start()
#sp2.start()
#sp1.join()
#sp2.join()
joinall(sp1,sp2)#等同于上述六步
print('Timeused:',time.clock()-start)
#('Timeused:',0.40398999999999985)以上是python协程的作用,希望对大家有所帮助。更多Python学习指导:python基础教程
本文教程操作环境:windows7系统Python 3.9.1,DELL G3电脑。
