别看pyhton有个GIL,但是在多线程编程时与java一样,为了保证数据的案例,还是需要用到锁Lock锁.
Lock不是重入锁,在同一个线程中不能多次acquire()
RLock才是重入锁
import threading from threading import Lock # 申明一把锁 lock = Lock() total = 0 def add(): global total, lock for i in range(1000000): # 获取锁 lock.acquire() total += 1 # 释放锁 lock.release() def sub(): global total,lock for i in range(1000000): # 获取锁 lock.acquire() total -= 1 # 释放锁 lock.release() if __name__ == '__main__': t1 = threading.Thread(target=add) t2 = threading.Thread(target=sub) t1.start() t2.start() t1.join() t2.join() print(total) # 并不等于0,说明不是等t1执行完了t2再执行. 这下打印肯定是0
日拱一卒无有尽,功不唐捐终入海