Python解決GIL鎖的辦法
GIL (Global Intercepto Lock)全域性直譯器鎖
當機器無論是有幾個核心,Python多執行緒都只會用到其中一個核心。利用htop命令可以測試出來。
這個並沒有解決資料共享出現不同步的問題
#-*- coding:utf-8 -*-
import threading
#子執行緒死迴圈
def test():
while True:
pass
t1 = threading.Thread(target=test)
t1.start()
#主執行緒死迴圈
while True:
pass
程式碼測試無論開幾個,都只是跑滿cpu100%,相當於一核心。
解決方法:
1. 使用多程序執行,此將要面臨解決共享資料的問題,多用queue或pipe解決;
2. 使用Python多執行緒load C的module執行。
from ctypes import *
form threading import Thread
#載入動態庫
lib = cdll.LoadLibrary("./libdeadloop.so")
#建立一個子執行緒,讓其執行c語言編寫的函式,此函式是一個死迴圈
t = Thread(target=lib.DeadLoop)
t.start()
while True:
pass