亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何與 ThreadPoolExecutor 并行運行代碼?

如何與 ThreadPoolExecutor 并行運行代碼?

千萬里不及你 2023-06-13 16:29:24
我真的是線程的新手,這讓我很困惑,我怎樣才能并行運行這段代碼?def search_posts(page):    page_url = f'https://jsonplaceholder.typicode.com/posts/{page}'    req = requests.get(page_url)    res = req.json()        title = res['title']        return titlepage = 1while True:    with ThreadPoolExecutor() as executer:        t = executer.submit(search_posts, page)        title = t.result()        print(title)    if page == 20:        break    page += 1另一個問題是我是否需要學習操作系統才能理解線程是如何工作的?
查看完整描述

1 回答

?
PIPIONE

TA貢獻1829條經驗 獲得超9個贊

這里的問題是您正在ThreadPoolExecutor為每個頁面創建一個新頁面。要并行執行操作,只創建一個ThreadPoolExecutor并使用它的map方法:


import concurrent.futures as cf

import requests



def search_posts(page):

    page_url = f'https://jsonplaceholder.typicode.com/posts/{page}'

    res = requests.get(page_url).json()

    return res['title']



if __name__ == '__main__':

    with cf.ThreadPoolExecutor() as ex: 

        results = ex.map(search_posts, range(1, 21))

    for r in results:

        print(r)

請注意,使用if __name__ == '__main__'包裝器是使您的代碼更具可移植性的好習慣。


使用線程時要記住一件事;python.org如果您使用的是 CPython(最常見的Python 實現),線程實際上不會并行運行。


為了使內存管理不那么復雜,一次只能有一個線程在 CPython 中執行 Python 字節碼。這是由 CPython 中的全局解釋器鎖(“GIL”)強制執行的。


好消息是,使用requests獲取網頁將花費大部分時間使用網絡 I/O。通常,GIL 是在 I/O 期間釋放的。


但是,如果您在輔助函數中進行計算(即執行 Python 字節碼),則應改用 a ProcessPoolExecutor。


如果您使用 aProcessPoolExecutor并且在 ms-windows 上運行,則需要if __name__ == '__main__'使用包裝器,因為在這種情況下Python 必須能夠在沒有副作用的情況下運行您的主程序。import


查看完整回答
反對 回復 2023-06-13
  • 1 回答
  • 0 關注
  • 119 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號