并發編程: https://www.processon.com/mindmap/5f636bac0791295dccc46f28

from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor import requests import os def get_page(url): print('<行程%s> get %s' %(os.getpid(),url)) respone=requests.get(url) if respone.status_code == 200: return {'url':url,'text':respone.text} def parse_page(res): res=res.result() print('<行程%s> parse %s' %(os.getpid(),res['url'])) parse_res='url:<%s> size:[%s]\n' %(res['url'],len(res['text'])) with open('db.txt','a') as f: f.write(parse_res) if __name__ == '__main__': urls=[ 'https://www.baidu.com', 'https://www.python.org', 'https://www.openstack.org', 'https://help.github.com/', 'http://www.sina.com.cn/' ] p=ProcessPoolExecutor(3) for url in urls: p.submit(get_page,url).add_done_callback(parse_page) #parse_page拿到的是一個future物件obj,需要用obj.result()拿到結果并發 爬蟲小程式
#### 有那幾種IO模型 blocking IO 阻塞IO nonblocking IO 非阻塞IO IO multiplexing 多路復用IO 也叫事件驅動IO(event driven IO) signal driven IO 信號驅動IO asynchronous IO 異步IO 由signal driven IO(信號驅動IO)在實際中并不常用,所以主要介紹其余四種IO Model, #### IO模型的區別是在那兩個階段上? 1)wait for data 等待資料準備 (Waiting for the data to be ready) 2)copy data 將資料從內核拷貝到行程中(Copying the data from the kernel to the process) blocking IO:在IO執行的兩個階段(等待資料和拷貝資料兩個階段)都被block了, 在非阻塞式IO:在等待資料階段是非阻塞的,用戶行程需要不斷的主動詢問kernel(內核)資料準備好了沒有, 需要注意,拷貝資料整個程序,行程仍然是屬于阻塞的狀態, 非阻塞IO模型絕不被推薦, 多路復用IO: 優勢在于可以處理多個連接,不適用于單個連接 當用戶行程呼叫了select,那么整個行程會被block,而同時,kernel會“監視”所有select負責的socket,當任何一個socket中的資料準備好了,select就會回傳,這個時候用戶行程再呼叫read操作,將資料從kernel拷貝到用戶行程, 對于每一個socket,一般都設定成為non-blocking,但是,整個用戶的process其實是一直被block的,只不過process是被select這個函式block, 而不是被socket IO給block, 異步IO:都不阻塞,當行程發起IO 操作之后,就直接回傳再也不理睬了,直到kernel發送一個信號,告訴行程說IO完成,在這整個程序中,行程完全沒有被block,IO模型
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/160294.html
標籤:Python
下一篇:檔案操作
