Python的协程

Python的并发

Python中由于存在GIL的问题,所以其在多线程上无法充分发挥多核的优势和威力,一般都会推荐使用多进程的方式来发挥多核的效率。
除了多进程的方式之外,还可以使用coroutine协程的方式来提升并发的处理效率。

进程、线程和协程

参考文章: https://www.cnblogs.com/zhaof/p/7536569.html

这篇文章关于进程、线程和协程之间的异同已经做了非常好的阐述,这里就不再单独展开篇幅分析和讨论了。

并发模式

目前并发模式应该是应用单线程的协程处理模式。多进程开启,进程中使用单线程模式,在线程中使用协程的方式。

代码示例

协程方式,下载图片

from bs4 import BeautifulSoup
import requests

from gevent import monkey; monkey.patch_all()
import gevent

from urllib.parse import urlparse
import shutil
import os

url = 'https://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fr=&sf=1&fmq=1526269427171_R&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word=%E5%A3%81%E7%BA%B8'
r = requests.get(url)
html = r.text
soup = BeautifulSoup(html, 'lxml')
links = soup.find_all('img')

print(links)
images = [i.get("src") for i in links if i.get("src") and len(i.get("src"))>0]
print("Len:" + str(len(images)))

def download_image(url):
    print("image:" + url)
    file_name = os.path.basename(url)
    response = requests.get(url, stream=True)
    with open(file_name, 'wb') as out_file:
        shutil.copyfileobj(response.raw, out_file)
    del response


tasks = []
for image in images:
        tasks.append(gevent.spawn(download_image, "http:" + image))

gevent.joinall(tasks)

运行结果:
这里写图片描述

参考资料

廖雪峰的gevent简明教程

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章