複数のスレッドが同じ関数にアクセスする場合、ロックメカニズムを明示的に実装する必要がありますか。
スレッドを使用したプログラムがあります。と の 2 つのスレッドがt1
ありt2
ます。t1
is foradd1()
とt2
is for 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
2. ロックを使わなくても大丈夫ですか?
上記のプログラムで定義されたロック メカニズムを使用しなくても、結果はスレッド 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
ありがとう!