問題描述
我發現在 Python 3.4 中有幾個不同的多處理/線程庫:multiprocessing vs 線程 vs asyncio.
I found that in Python 3.4 there are few different libraries for multiprocessing/threading: multiprocessing vs threading vs asyncio.
但我不知道該使用哪一個或者是推薦的".他們做同樣的事情,還是不同?如果是這樣,哪一個用于什么?我想在我的計算機上編寫一個使用多核的程序.但我不知道我應該學習哪個庫.
But I don't know which one to use or is the "recommended one". Do they do the same thing, or are different? If so, which one is used for what? I want to write a program that uses multicores in my computer. But I don't know which library I should learn.
推薦答案
它們用于(稍微)不同的目的和/或要求.CPython(一個典型的主線 Python 實現)仍然具有 全局解釋器鎖,因此是一個多線程應用程序(現在實現并行處理的標準方法)不是最理想的.這就是為什么 multiprocessing
可能 優于 threading
的原因.但并不是每個問題都可以有效地分解為[幾乎獨立的]部分,因此可能需要繁重的進程間通信.這就是為什么 multiprocessing
通常可能不優于 threading
.
They are intended for (slightly) different purposes and/or requirements. CPython (a typical, mainline Python implementation) still has the global interpreter lock so a multi-threaded application (a standard way to implement parallel processing nowadays) is suboptimal. That's why multiprocessing
may be preferred over threading
. But not every problem may be effectively split into [almost independent] pieces, so there may be a need in heavy interprocess communications. That's why multiprocessing
may not be preferred over threading
in general.
asyncio
(這種技術不僅在 Python 中可用,其他語言和/或框架也有它,例如 Boost.ASIO) 是一種有效處理來自許多同時源的大量 I/O 操作而無需并行代碼執行的方法.所以它只是針對特定任務的解決方案(確實是一個很好的解決方案!),而不是一般的并行處理.
asyncio
(this technique is available not only in Python, other languages and/or frameworks also have it, e.g. Boost.ASIO) is a method to effectively handle a lot of I/O operations from many simultaneous sources w/o need of parallel code execution. So it's just a solution (a good one indeed!) for a particular task, not for parallel processing in general.
這篇關于Python 3 中的多處理、多線程和異步的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!