多執行緒同步的兩種方式
阿新 • • 發佈:2019-02-13
這是我昨天練習的多執行緒同步問題
解決方法一:輪詢
import threading
import time
count=500 #全域性變數
user_input1=input('請輸入金額:') #終端輸入消費金額
user_input2=input('請輸入消費金額:')
flag=False #這裡設定標識位,為False時表示空閒
def pos1():
global count,user_input,flag
while flag: #flag==True 等待
time.sleep(0.01) #睡眠等空閒再喚醒
flag=True #到這裡表示標識位為False 此時把該標識位設定為True
if int(user_input1)<=500: #判斷輸入金額是否超過餘額
count=count-int(user_input1)
print('消費成功')
else:
print('你的餘額不足')
#操作完成 把標識位重新設定成False
flag=False
print('餘額為%d'%count)
def pos2():
global count,user_input,flag
while flag:
time.sleep(0.01)
flag=True
if int(user_input2)<=count:
count=count-int(user_input2)
print('消費成功')
else:
print('你的餘額不足')
flag=False
print('餘額為%d'%count)
t1=threading.Thread(target=pos1) # 建立子執行緒,並在指定函式pos1執行
t1.start()
t2=threading.Thread(target=pos2) #建立子執行緒,並在指定函式pos2執行
t2.start()
方式二:加鎖
import threading
import time
count=500 #總餘額
mutex=threading.Lock() #建立鎖
def pos1():
global count,flag
mutex.acquire() #上鎖
if count>=400: #判斷消費金額是否超過餘額
count-=400
print('消費成功')
else:
print('你的餘額不足')
mutex.release() #解鎖
print('餘額為%d'%count)
def pos2():
global count,flag
mutex.acquire()
if count>=300:
count-=300
print('消費成功')
else:
print('你的餘額不足')
mutex.release()
print('餘額為%d'%count)
t1=threading.Thread(target=pos1) #建立子執行緒,並在指定函式pos1執行
t1.start()
t2=threading.Thread(target=pos2) #建立子執行緒,並在指定函式pos2執行
t2.start()