锁:
import threading,time def addNum(): global num lock.acquire() #获取锁 temp=num time.sleep(0.01) # print('ok') num=temp-1 lock.release() #释放锁 #锁保证线程没有执行完CPU不会执行别的线程 num=100 lst_Thread=[] lock=threading.Lock() #实例锁对象 for i in range(100): t=threading.Thread(target=addNum) t.start() lst_Thread.append(t) for t in lst_Thread: #等到所有线程执行完毕,在执行主线程 t.join() print('num:',num)
递归锁:
import time,threading class Account: def __init__(self,_id,balance): self.id=_id self.balance=balance # 每一个用户都有自己的一个锁,保证数据安全性 self.lock=threading.RLock() #递归锁 def withdraw(self,amount): #取钱 with self.lock: self.balance-=amount # 相当于 # self.lock.acquire() # self.balance -= amount # self.lock.release() def deposit(self,amount): #存钱 with self.lock: self.balance+=amount def drawcash(self,amount): #在算过利息后提钱 with self.lock: interest=0.05 count=amount+amount*interest # lock.acquire中嵌套lock.acquire self.withdraw(count) def transfer(_from,to,amount): #不同账户之间转钱 #锁不能在这,因为如果别的操作在对balance进行操作的时候,数据不安全 _from.withdraw(amount) to.deposit(amount) a=Account('001',1000) b=Account('002',500) t1=threading.Thread(target=transfer(a,b,100)) t1.start() t2=threading.Thread(target=transfer(b,a,150)) t2.start() t1.join() t2.join() print(a.balance) print(b.balance)