原文:https://medium.com/building-things-on-the-internet/40e9b2b36148html
譯文:https://segmentfault.com/a/1190000000414339 python
#from multiprocessing import Pool from multiprocessing.dummy import Pool as ThreadPool import requests urls = [ 'http://www.python.org', 'http://www.python.org/about/', 'http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html', 'http://www.python.org/doc/', 'http://www.python.org/download/', 'http://www.python.org/getit/', 'http://www.python.org/community/', 'https://wiki.python.org/moin/', 'http://planet.python.org/', 'https://wiki.python.org/moin/LocalUserGroups', 'http://www.python.org/psf/', 'http://docs.python.org/devguide/', 'http://www.python.org/community/awards/', 'http://www.python.org/community/fuck/' # etc.. ] pool = ThreadPool(4) # Sets the pool size to 4 def code(x): r = requests.get(x) _code = r.status_code print(f"{x} 狀態碼是:{_code}") results = pool.map(code, urls) pool.close() pool.join()
在生產環境中,咱們能夠爲 CPU 密集型任務和 IO 密集型任務分別選擇多進程和多線程庫來進一步提升執行速度——這也是解決死鎖問題的良方。此外,因爲 map 函數並不支持手動線程管理,反而使得相關的 debug 工做也變得異常簡單。segmentfault