Python:Day28 同步锁

时间:2022-08-06 15:27:55

同步锁:

Python不是有一把锁了吗?为什么还要加锁?

Python解释器的GIL的作用是同一时刻只有一个线程被CPU执行,而同步锁的作用同一时刻只有一个线程对锁定代码块操作

如果不加锁,当多个线程对同一数据操作的时候就有可能出问题,代码如下:

import threading
import time def minus_num():
global num
temp = num
time.sleep(0.001)
num = temp - 1 num = 100
threads = []
for i in range(100):
t = threading.Thread(target=minus_num)
threads.append(t)
for t in threads:
t.start()
for k in threads:
k.join()
print(num)

加上同步锁后代码:

import threading
import time def minus_num():
global num
r.acquire()
temp = num
time.sleep(0.001)
num = temp - 1
r.release() num = 100
threads = []
r = threading.Lock() # 创建一把锁,这个锁在任意时刻都只能被一个线程获取。
for i in range(100):
t = threading.Thread(target=minus_num)
threads.append(t)
for t in threads:
t.start()
for k in threads:
k.join()
print(num)  # 0

死锁、递规锁

import threading
import time class MyThread(threading.Thread):
def doA(self):
lockA.acquire()
print("%s get the lockA" % self.name)
time.sleep(1)
lockB.acquire()
print("%s get the lockB" % self.name)
lockA.release()
lockB.release() def doB(self):
lockB.acquire()
print("%s get the lockB" % self.name)
time.sleep(1)
lockA.acquire()
print("%s get the lockA" % self.name)
lockA.release()
lockB.release() def run(self):
self.doA()
self.doB() lockA = threading.Lock()
lockB = threading.Lock() threads = []
for i in range(5):
threads.append(MyThread()) for i in threads:
i.start() for i in threads:
i.join() print("----------the end----------")

之所以出现死锁的现象是因为一个线程需要两把或两把以上的锁,且出现了锁套锁,并且其中一个锁被其它线程占用且不能释放,这样就造成了死其锁。