python3 协程
https://www.cnblogs.com/ZCQPCY/articles/9605954.html——了解迭代器和生成器
一、协程
协程是python中另外一种实现多任务的方式。
使用yield实现协程:
(死循环——请不要轻易执行)
__author__ = 'Administrator'
import time
def task1():
while True:
print("————1————")
time.sleep(0.1)
yield
def task2():
while True:
print("————2————")
time.sleep(0.1)
yield
def main():
t1=task1()
t2=task2()
while True:
next(t1)
next(t2)
if __name__ == '__main__':
main()
二、gevent
python中实现协程是基于Gevent模块,Gevent模块内部封装了greenlet模块;greenlet模块实现了在单线程中切换状态,Gevent模块在此之上还实现了遇到I/O操作自动切换,使程序运行更快;但是Gevent只在遇到自己认识的I/O操作时切换,所以需要使用Gevent包的一个模块:猴子补丁,使用了这个补丁,Gevent会直接修改在它之后导入的模块中的I/O操作,使其可以让Gevent识别,从而开启协程。
Greenlet与Gevent模块都是python的第三方模块,需安装使用。
pip install gevent
__author__ = 'Administrator'
import gevent
from gevent import monkey
import random
import time
# 将程序中用到的耗时操作的代码,换为gevent中自己实现的模块,
# monkey补丁会将在它之后导入的模块的IO操作打包,使gevent认识它们
monkey.patch_all()
def task(task_name):
for i in range(10):
print(task_name,i)
time.sleep(random.random())
gevent.joinall([
gevent.spawn(task,"扫地"),
gevent.spawn(task,"擦桌子"),
gevent.spawn(task,"烧水"),
gevent.spawn(task,"煮饭")
])
############################
扫地 0
擦桌子 0
烧水 0
煮饭 0
煮饭 1
扫地 1
擦桌子 1
烧水 1
扫地 2
烧水 2
煮饭 2
烧水 3
擦桌子 2
煮饭 3
擦桌子 3
扫地 3
烧水 4
擦桌子 4
烧水 5
烧水 6
煮饭 4
煮饭 5
扫地 4
擦桌子 5
烧水 7
烧水 8
擦桌子 6
擦桌子 7
烧水 9
扫地 5
煮饭 6
擦桌子 8
扫地 6
扫地 7
煮饭 7
煮饭 8
擦桌子 9
煮饭 9
扫地 8
扫地 9
图片下载器:
__author__ = 'Administrator'
import urllib.request
import gevent
from gevent import monkey
monkey.patch_all()
def download(img_name,img_url):
req=urllib.request.urlopen(img_url)
img_data=req.read()
with open(img_name,"wb") as f:
f.write(img_data)
def main():
gevent.joinall([
gevent.spawn(download, "1.jpg", "https://imgsa.baidu.com/news/q%3D100/sign=b3e0740b047b02080ac93be152d8f25f/242dd42a2834349bdedd322bc7ea15ce37d3be41.jpg"),
gevent.spawn(download,"2.jpg","https://imgsa.baidu.com/news/q%3D100/sign=0e8b8e16da3f8794d5ff4c2ee21a0ead/8326cffc1e178a8225cf120ef803738da877e8a9.jpg")
])
if __name__ == '__main__':
main()


浙公网安备 33010602011771号