Thread 主要是用來有效利用 CPU 資源的方法。但 Python 使用全局解釋鎖(GIL)的原因,程式碼並不能同時在多核上並行的執行,因此 Python 實際上並無法真的做並行的。
Python 在 Thread 提供兩組接口,一組是thread模塊,提供基礎的,低等級(Low Level)接口,使用Function作為線程的運行體。還有一組是threading模塊,提供更容易使用的基於對象的接口(類似於Java),可以繼承Thread對象來實現線程,還提供了其它一些線程相關的對象,例如Timer,Lock。 原文網址
使用 thread 模塊的例子 原文網址
import thread
def worker:
"""thread worker function"""
print 'Worker' thread.start_new_thread(worker)
使用 threading 模塊的例子 原文網址
import threading
def worker:
"""thread worker function"""
print 'Worker'
t = threading.Thread(target=worker)
t.start