Python多進程VS多線程

來源:互聯網
上載者:User

標籤:end   ted   worker   res   簡單函數   adp   div   c函數   使用   

多線程:適用於處理I/O密集型任務和並發執行的阻塞操作
多進程:適用於處理計算密集型任務

 

# 多進程import itertoolsfrom concurrent.futures import ProcessPoolExecutorresult = []# 回呼函數,通過add_done_callback任務完成後調用def when_done(r):    # when_done在主進程中運行    result.append(r.result())"""    with class_a() as a: 上下文管理器"""with ProcessPoolExecutor() as pool:    for keep_stock_threshold, buy_change_threshold in             itertools.product(keep_stock_list, buy_change_list):        """            submit提交任務:使用calc函數和的參數通過submit提交到獨立進程            提交的任務必須是簡單函數,進程並行不支援類方法、閉包等            函數參數和傳回值必須相容pickle序列化,進程間的通訊需要        """        future_result = pool.submit(calc, keep_stock_threshold,                                    buy_change_threshold)        # 當進程完成任務即calc運行結束後的回呼函數        future_result.add_done_callback(when_done)print(sorted(result)[::-1][:10])

 

# 多線程from concurrent.futures import ThreadPoolExecutorresult = []def when_done(r):    result.append(r.result())with ThreadPoolExecutor(max_workers=8) as pool:    for keep_stock_threshold, buy_change_threshold in             itertools.product(keep_stock_list, buy_change_list):        future_result = pool.submit(calc, keep_stock_threshold,                                    buy_change_threshold)        future_result.add_done_callback(when_done)

 

Python多進程VS多線程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.