<?xml version="1.0" encoding="UTF-8" ?><oembed><version>1.0</version><provider_name>Jui-Nan Lin&#039;s Blog</provider_name><provider_url>https://jnlin.org</provider_url><author_name>jnlin</author_name><author_url>https://jnlin.org/author/jnlin/</author_url><title>Python 的 GIL (Global Interpreter Lock)</title><html>&lt;p&gt;前幾個月在做專案的時候，發現用 &lt;a href=&quot;http://code.google.com/p/modwsgi/&quot;&gt;mod_wsgi&lt;/a&gt; + &lt;a href=&quot;http://webpy.org/&quot;&gt;web.py&lt;/a&gt; 寫的程式，理論上支援 multi-thread，應該可以完全利用在多核 CPU Server 的優勢；但實際上跑的時候，會有沒辦法把 CPU Resource 吃完的問題。當時因為時間很趕，想到的解法就是多跑幾個 Process：     &lt;br /&gt;&lt;code&gt;     &lt;br /&gt;&lt;VirtualHost *:80&gt;&#160; &lt;br /&gt;&#160;&#160; DocumentRoot “/srv/web/webroot&quot;&#160; &lt;br /&gt;&#160;&#160; ServerName python.example.com&#160; &lt;br /&gt;&#160;&#160; WSGIProcessGroup pythonexample&#160; &lt;br /&gt;&#160;&#160; WSGIDaemonProcess pythonexample processes=&lt;font color=&quot;#ff0000&quot;&gt;16&lt;/font&gt; threads=128 maximum-requests=1024 display-name=%{GROUP}       &lt;br /&gt;&lt;/VirtualHost&gt; &lt;/code&gt;&lt;/p&gt;  &lt;p&gt;在 &lt;a href=&quot;http://coscup.org/&quot;&gt;COSCUP&lt;/a&gt; 跟 &lt;a href=&quot;http://www.facebook.com/lwhsu&quot;&gt;lwhsu&lt;/a&gt; 聊到這件事，他講到 CPython 的 GIL，回來查了一下果然就是這個原因。剛好 Web 不需要在每個 thread 之間互相傳資料，所以可以直接用多個 Process 解掉這個問題。&lt;/p&gt;  &lt;p&gt;雖然 Python 在執行前就把程式碼轉成 byte code了，但因為這個 Lock 是實做在 CPython 的 Bytecode Interpreter 裡面，所以導致了同時只會有一個 thread 執行 Python bytecode，也因此無法利用到多核 CPU 的優勢 ((&lt;a href=&quot;http://stackoverflow.com/questions/4748787/python-threading-and-gil&quot;&gt;Stackoverflow: Python threading and gil&lt;/a&gt;))。&lt;/p&gt;  &lt;p&gt;除了多跑幾個 Process 之外，也可以用 &lt;a href=&quot;http://docs.python.org/library/ctypes.html&quot;&gt;ctypes&lt;/a&gt; 配合用 C 寫的 library 來解決這個問題，不過以 Web 應用來說，寫 C 的機會不高就是了。&lt;/p&gt;</html><type>rich</type></oembed>