python程序和執行緒中的兩個鎖

2022-09-05 12:54:11 字數 909 閱讀 9099

gil鎖(全域性直譯器鎖)

gil鎖的作用是:每個程序中同一時間只能有乙個程序鏈結cpu,鏈結以後,cpu執行100個cpu指令以後,再由別的執行緒去鏈結cpu,

rlock鎖(可重入鎖/遞迴鎖)

import

time

import

threading

lock =threading.rlock()

n = 10

deftask(i):

print('

這段**不加鎖

',i)

#print('hello word')

lock.acquire() #

加鎖,此區域的**同一時刻只能有乙個執行緒執行,並且只能是加鎖的這個程序執行,cpu執行完100個cpu指令以後又返回來執行這個程序,直到程序執行完畢,再去排程別的程序

print('

hello word')

global

n

print('

當前執行緒

',i,'

讀取到的n值為:

',n)

n =i

time.sleep(1)

print('

當前執行緒

',i,'

修改n值為:

',n)

lock.release()

#釋放鎖

for i in range(10):

t = threading.thread(target=task,args=(i,))

t.start()

#for迴圈迴圈的是準備好的乙個執行緒例項,至於這個例項要執行多久,例項並不管他

#start表示我已近準備好了,你可以排程我了

Python兩個程序溝通問題

在父程序中建立兩個子程序,乙個往queue寫資料,乙個從queue讀資料,用同乙個訊息佇列 frommultiprocessingimportqueue,process importtime,random defwrite q forvaluein a b c d print write put s...

Python中的程序和執行緒

from multiprocessing import process process process target 函式,name 程序的名字,args 給函式傳遞的引數 process.start 啟動程序並執行任務 process.run 只是執行了任務但是沒有啟動程序 process.ter...

基於python多程序的兩個練習

練習1 求100000以內質數之和 分別使用4個程序和10個程序做這件事,並且分別 統計執行時間,進行對比 import time from multiprocessing import process def timeis f args,kwargs start time time.time re...