本文讲python中的四种锁
Lock互斥锁
使用前
num = 0
def a():
global num
for _ in range(10000000):
num += 1
def b():
global num
for _ in range(10000000):
num += 1
if __name__ == '__main__':
t1=Thread(target=a)
t1.start()
t2=Thread(target=b)
t2.start()
t1.join()
t2.join()
print(num) #基本永远会小于20000000
使用后
num = 0
def a(lock):
global num
for _ in range(1000000):
with lock:
num += 1
def b(lock):
global num
for _ in range(1000000):
with lock:
num += 1
if __name__ == '__main__':
lock = threading.Lock()
t1=Thread(target=a, args=(lock,))
t1.start()
t2=Thread(target=b, args=(lock,))
t2.start()
t1.join()
t2.join()
print(num) #永远会输出20000000
RLock重用锁
#在之前的代码中永远不可能出现锁在没释放之前重新获得锁,但rlock可以做到,但只能发生在一个线程中,如:
num = 0
def a(lock):
with lock:
print("我是A")
b(lock)
def b(lock):
with lock:
print("我是b")
if __name__ == '__main__':
lock = threading.Lock()
t1 = Thread(target=a, args=(lock,))
t1.start() #会发生死锁,因为在第一次还没释放锁后,b就准备上锁,并阻止a释放锁
使用后
if __name__ == '__main__':
lock = threading.RLock() #只需要改变锁为RLock程序马上恢复
t1 = Thread(target=a, args=(lock,))
t1.start()
Condition同步锁
#这个程序我们模拟甲乙对话
Jlist = ["在吗", "干啥呢", "去玩儿不", "好吧"]
Ylist = ["在呀", "玩儿手机", "不去"]
def J(list):
for i in list:
print(i)
time.sleep(0.1)
def Y(list):
for i in list:
print(i)
time.sleep(0.1)
if __name__ == '__main__':
t1 = Thread(target=J, args=(Jlist,))
t1.start()
t1.join()
t2 = Thread(target=Y, args=(Ylist,))
t2.start()
t2.join() #上面的程序输出后发现效果就是咱们想要的,但是我们每次输出后都要等待0.1秒,也无法正好确定可以拿到时间片的最短时间值,并且不能保证每次正好都是另一个线程执行。因此,我们用以下方式,完美解决这些问题。
使用后
Jlist = ["在吗", "干啥呢", "去玩儿不", "好吧"]
Ylist = ["在呀", "玩儿手机", "不去","哦"]
def J(cond, list):
for i in list:
with cond:
print(i)
cond.notify()
cond.wait()
def Y(cond, list):
for i in list:
with cond:
cond.wait()
print(i)
cond.notify()
if __name__ == '__main__':
cond = threading.Condition()
t1 = Thread(target=J, args=(cond, Jlist))
t2 = Thread(target=Y, args=(cond, Ylist))
t2.start()
t1.start() #一定保证t1启动在t2之后,因为notify发送的信号要被t2接受到,如果t1先启动,会发生阻塞。
Seamplore信号量
使用前
class B(threading.Thread):
def __init__(self, name):
super().__init__()
self.name = name
def run(self):
time.sleep(1)
print(self.name)
class A(threading.Thread):
def __init__(self):
super().__init__()
def run(self):
for i in range(100):
b = B(i)
b.start()
if __name__ == '__main__':
a = A()
a.start() #执行后发现不断在输出
使用后
class B(threading.Thread):
def __init__(self, name, sem):
super().__init__()
self.name = name
self.sem = sem
def run(self):
time.sleep(1)
print(self.name)
sem.release()
class A(threading.Thread):
def __init__(self, sem):
super().__init__()
self.sem = sem
def run(self):
for i in range(100):
self.sem.acquire()
b = B(i, self.sem)
b.start()
if __name__ == '__main__':
sem = threading.Semaphore(value=3)
a = A(sem)
a.start() #通过执行上面的代码,我们发现一次只能输出三个数字,sem控制访问并发量
Event事件
import time
import threading
class MyThread(threading.Thread):
def __init__(self, name, event):
super().__init__()
self.name = name
self.event = event
def run(self):
print('Thread: {} start at {}'.format(self.name, time.ctime(time.time())))
# 等待event.set()后,才能往下执行
self.event.wait()
print('Thread: {} finish at {}'.format(self.name, time.ctime(time.time())))
event = threading.Event()
# 定义五个线程
threads = [MyThread(str(i), event) for i in range(1,5)]
# 重置event,使得event.wait()起到阻塞作用
event.clear()
# 启动所有线程
[t.start() for t in threads]
print('等待5s...')
time.sleep(5)
print('唤醒所有线程...')
event.set()
# output:
'''
Thread: 1 start at Sun May 13 20:38:08 2018
Thread: 2 start at Sun May 13 20:38:08 2018
Thread: 3 start at Sun May 13 20:38:08 2018
Thread: 4 start at Sun May 13 20:38:08 2018
等待5s...
唤醒所有线程...
Thread: 1 finish at Sun May 13 20:38:13 2018
Thread: 4 finish at Sun May 13 20:38:13 2018
Thread: 2 finish at Sun May 13 20:38:13 2018
Thread: 3 finish at Sun May 13 20:38:13 2018
'''
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。