天天看點

Python-開發之路-協程舉例

Python中的協程主要是使用gevent的功能,需要安裝第三方子產品gevent

單輪處理效率來講:協程比多線程效率高,但是設計大量io工作時,建議還是用多線程

代碼如下:

#!/usr/bin/env python
# -- coding = 'utf-8' --
# Author Allen Lee
# Python Version 3.5.1
# OS Windows 7
from gevent import monkey;monkey.patch_all()
import gevent,os
import requests

def f(url):
    print('GET: %s' %url)
    resp = requests.get(url)
    data = resp.text
    print('%d bytes received from %s.' %(len(data),url))
#當有IO大量回調任務時,比如,給mysql插入資料,多線程會比協程高效,比如爬蟲
gevent.joinall([
    gevent.spawn(f,'https://www.python.org/'),  #子線程一
    gevent.spawn(f,'https://www.yahoo.com/'),   #子線程二
    gevent.spawn(f,'https://github.com/'),      #子線程三
])