當多個線程訪問同一個函數時,我們是否需要明確或不需要實現鎖機制。Python:通過多線程同時訪問一個沒有鎖定的函數mechansim
我有一個使用線程的程序。有兩個線程,t1
和t2
。 t1
爲add1()
和t2
爲螺紋的subtract1()
。無論同時訪問同一個功能myfunction(caller,num)
1.我已經定義在給定的程序中使用的變量functionLock
一個簡單的鎖定機構。這是可靠的還是我們需要修改它?
import time, threading
functionLock = '' # blank means lock is open
def myfunction(caller,num):
global functionLock
while functionLock!='': # check and wait until the lock is open
print "locked by "+ str(functionLock)
time.sleep(1)
functionLock = caller # apply lock
total=0
if caller=='add1':
total+=num
print"1. addition finish with Total:"+str(total)
time.sleep(2)
total+=num
print"2. addition finish with Total:"+str(total)
time.sleep(2)
total+=num
print"3. addition finish with Total:"+str(total)
else:
time.sleep(1)
total-=num
print"\nSubtraction finish with Total:"+str(total)
print '\n For '+caller+'() Total: '+str(total)
functionLock='' # release the lock
def add1(arg1, arg2):
print '\n START add'
myfunction('add1',10)
print '\n END add'
def subtract1():
print '\n START Sub'
myfunction('sub1',100)
print '\n END Sub'
def main():
t1 = threading.Thread(target=add1, args=('arg1','arg2'))
t2 = threading.Thread(target=subtract1)
t1.start()
t2.start()
if __name__ == "__main__":
main()
輸出如下:
START add
START Sub
1. addition finish with Total:10
locked by add1
locked by add1
2. addition finish with Total:20
locked by add1
locked by add1
3. addition finish with Total:30
locked by add1
For add1() Total: 30
END add
Subtraction finish with Total:-100
For sub1() Total: -100
END Sub
二是確定它不使用鎖?
即使我沒有使用上述程序中定義的鎖定機制,結果對於線程t1和t2來說都是一樣的。這是否意味着python在多個線程訪問同一個函數時自動實現鎖定。
的程序的輸出,而無需使用該鎖,functionLock
,在上述程序
START add
START Sub
1. addition finish with Total:10
Subtraction finish with Total:-100
For sub1() Total: -100
END Sub
2. addition finish with Total:20
3. addition finish with Total:30
For add1() Total: 30
END add
謝謝!
'total'不是全球性的,雖然 – Sebastian 2013-03-14 07:59:52
@塞巴斯蒂安感謝您的評論,改變了我的答案。 – 2013-03-14 12:32:04