爲了更好的多線程性能,在對象建立或者更新時,若數據大於2047字節則 Python 的 GIL 會被釋放。 執行計算密集型任務如壓縮或哈希時釋放 GIL

 

hashlib — Secure hashes and message digests — Python 3.8.3 documentation https://docs.python.org/3.8/library/hashlib.htmlhtml

For better multithreading performance, the Python GIL is released for data larger than 2047 bytes at object creation or on update.python

hashlib --- 安全哈希與消息摘要 — Python 3.8.3 文檔 https://docs.python.org/zh-cn/3.8/library/hashlib.html安全

術語對照表 — Python 3.8.3 文檔 https://docs.python.org/zh-cn/3.8/glossary.html#term-gil多線程

 global interpreter lock -- 全局解釋器鎖併發

CPython 解釋器所採用的一種機制,它確保同一時刻只有一個線程在執行 Python bytecode。此機制經過設置對象模型(包括 dict 等重要內置類型)針對併發訪問的隱式安全簡化了 CPython 實現。給整個解釋器加鎖使得解釋器多線程運行更方便,其代價則是犧牲了在多處理器上的並行性。性能

不過,某些標準庫或第三方庫的擴展模塊被設計爲在執行計算密集型任務如壓縮或哈希時釋放 GIL。此外,在執行 I/O 操做時也老是會釋放 GIL。ui

建立一個(以更精細粒度來鎖定共享數據的)「自由線程」解釋器的努力從未得到成功,由於這會犧牲在普通單處理器狀況下的性能。據信克服這種性能問題的措施將致使實現變得更復雜,從而更難以維護。this

 

global interpreter lockspa

The mechanism used by the CPython interpreter to assure that only one thread executes Python bytecodeat a time. This simplifies the CPython implementation by making the object model (including critical built-in types such as dict) implicitly safe against concurrent access. Locking the entire interpreter makes it easier for the interpreter to be multi-threaded, at the expense of much of the parallelism afforded by multi-processor machines.線程

However, some extension modules, either standard or third-party, are designed so as to release the GIL when doing computationally-intensive tasks such as compression or hashing. Also, the GIL is always released when doing I/O.

Past efforts to create a 「free-threaded」 interpreter (one which locks shared data at a much finer granularity) have not been successful because performance suffered in the common single-processor case. It is believed that overcoming this performance issue would make the implementation much more complicated and therefore costlier to maintain.

相關文章
相關標籤/搜索