1. 程式人生 > >python多執行緒——1、GIL

python多執行緒——1、GIL

一、GIL是什麼?

       執行緒全域性鎖(Global Interpreter lock),python保護執行緒安全而採取的獨立執行緒執行的限制。

     1、明確一點GIL並不是python的特性,python完全可以不依賴GIL,它是在實現python直譯器(Cpython)時引入的一個概念,Cpython是大部分情況下預設使用的python執行環境。

a、python中一個執行緒對應C語言中的一個執行緒
b、gil使得同一個時刻只有一個執行緒在一個cpu上執行位元組碼,無法將多個執行緒對映到多個cpu上
c、gil會根據執行的位元組碼函式以及時間片釋放gil,gil在遇到io操作時候主動釋放(使得gil在多io操作的情況下是非常適用的)

 

#gil global interpreter lock (cpython)
#python中一個執行緒對應C語言中的一個執行緒
#gil使得同一個時刻只有一個執行緒在一個cpu上執行位元組碼,無法將多個執行緒對映到多個cpu上
#gil會根據執行的位元組碼函式以及時間片釋放gil,gil在遇到io操作時候主動釋放(使得gil在多io操作的情況下是非常適用的)

# import dis
# def add(a):
#     a = a+1
#
# print(dis.dis(add))

total = 0
def add():
    global total
    #1.do something1
    #2. io操作
    #3.do someting3
    for i in range(1000000):
        total += 1
def desc():
    global total
    for i in range(1000000):
        total -= 1
import threading
thread1 = threading.Thread(target=add)
thread2 = threading.Thread(target=desc)
thread1.start()
thread2.start()

thread1.join()
thread2.join()
print(total)
#total不為0