-RLock解决死锁
死锁:
from threading import Thread,Lock
import time
mutexA=Lock()
mutexB=Lock()
class MyThread(Thread):
def run(self):
self.func1()
self.func2()
def func1(self):
mutexA.acquire()
print('%s 拿到A锁' %self.name)
mutexB.acquire()
print('%s 拿到B锁' %self.name)
mutexB.release()
mutexA.release()
def func2(self):
mutexB.acquire()
print('%s 拿到B锁' %self.name)
time.sleep(2)
mutexA.acquire()
print('%s 拿到A锁' %self.name)
mutexA.release()
mutexB.release()
if __name__=='__main__':
for i in range(10):
t=MyThread()
t.start()
结果:
Thread-1 拿到A锁
Thread-1 拿到B锁 (之后线程一释放了AB锁执行func2又拿到了B锁)
Thread-1 拿到B锁
Thread-2 拿到A锁
。。。就卡住不动了
解决方法,使用递归锁Rlock=Lock+counter
递归锁的特点:可以只要一把锁,可以多次acquiere,acquire一次则counter加1,counter只要计数不为0,其他人就抢不到锁,必须得release多次,release一次counter 减1,直到counter 为0
from threading import Thread,RLock
import time
mutexA=mutexB=RLock()
class MyThread(Thread):
def run(self):
self.func1()
self.func2()
def func1(self):
mutexA.acquire()
print('%s 拿到A锁' %self.name)
mutexB.acquire()
print('%s 拿到B锁' %self.name)
mutexB.release()
print('%s 释放了B锁' %self.name)
mutexA.release()
print('%s 释放了到A锁' %self.name)
def func2(self):
mutexB.acquire()
print('%s 拿到B锁' %self.name)
time.sleep(2)
mutexA.acquire()
print('%s 拿到A锁' %self.name)
mutexA.release()
print('%s 释放了到A锁' %self.name)
mutexB.release()
print('%s 释放了B锁' %self.name)
if __name__=='__main__':
for i in range(10):
t=MyThread()
t.start()
结果:解决了死锁问题
Thread-1 拿到A锁
Thread-1 拿到B锁
Thread-1 释放了B锁
Thread-1 释放了到A锁
Thread-2 拿到A锁
Thread-2 拿到B锁
Thread-2 释放了B锁
Thread-2 释放了到A锁
Thread-3 拿到A锁
Thread-3 拿到B锁
Thread-3 释放了B锁
Thread-3 释放了到A锁
Thread-1 拿到B锁
Thread-1 拿到A锁
Thread-1 释放了到A锁
Thread-1 释放了B锁
Thread-4 拿到A锁
Thread-4 拿到B锁
Thread-4 释放了B锁
Thread-4 释放了到A锁
Thread-5 拿到A锁
Thread-5 拿到B锁
Thread-5 释放了B锁
Thread-5 释放了到A锁
Thread-6 拿到A锁
Thread-6 拿到B锁
Thread-6 释放了B锁
Thread-6 释放了到A锁
Thread-7 拿到A锁
Thread-7 拿到B锁
Thread-7 释放了B锁
Thread-7 释放了到A锁
Thread-2 拿到B锁
Thread-2 拿到A锁
Thread-2 释放了到A锁
Thread-2 释放了B锁
Thread-8 拿到A锁
Thread-8 拿到B锁
Thread-8 释放了B锁
Thread-8 释放了到A锁
Thread-3 拿到B锁
Thread-3 拿到A锁
Thread-3 释放了到A锁
Thread-3 释放了B锁
Thread-9 拿到A锁
Thread-9 拿到B锁
Thread-9 释放了B锁
Thread-9 释放了到A锁
Thread-10 拿到A锁
Thread-10 拿到B锁
Thread-10 释放了B锁
Thread-10 释放了到A锁
Thread-4 拿到B锁
Thread-4 拿到A锁
Thread-4 释放了到A锁
Thread-4 释放了B锁
Thread-5 拿到B锁
Thread-5 拿到A锁
Thread-5 释放了到A锁
Thread-5 释放了B锁
Thread-6 拿到B锁
Thread-6 拿到A锁
Thread-6 释放了到A锁
Thread-6 释放了B锁
Thread-7 拿到B锁
Thread-7 拿到A锁
Thread-7 释放了到A锁
Thread-7 释放了B锁
Thread-8 拿到B锁
Thread-8 拿到A锁
Thread-8 释放了到A锁
Thread-8 释放了B锁
Thread-9 拿到B锁
Thread-9 拿到A锁
Thread-9 释放了到A锁
Thread-9 释放了B锁
Thread-10 拿到B锁
Thread-10 拿到A锁
Thread-10 释放了到A锁
Thread-10 释放了B锁
- 信号量
信号量机制指的是只有一把锁,但是资源数目不再是1,为n,意思可以理解为有五个人可以打开这个锁,不再是只有一把钥匙,而是n把钥匙
from threading import Thread,Semaphore,current_thread
import time,random
sm=Semaphore(5) #表示有5个资源
def task():
with sm: #指的是加锁
print('%s is runing' %current_thread().getName())
time.sleep(random.randint(1,3))
if __name__=='__main__':
for i in range(10):
t=Thread(target=task)
t.start()
#运行过程会发现,会不定数的出现线程,意思是走几个补几个
- Event事件
如果程序中的其他线程需要通过判断某个线程的状态来确定自己下一步的操作:
1、需要使用threading库中的Event对象。 对象包含一个可由线程设置的信号标志,它允许线程等待某些事件的发生。
2、在 初始情况下,Event对象中的信号标志被设置为假。如果有线程等待一个Event对象, 而这个Event对象的标志为假,那么这个线程将会被一直阻塞直至该标志为真。一个线程如果将一个Event对象的信号标志设置为真,它将唤醒所有等待这个Event对象的线程。如果一个线程等待一个已经被设置为真的Event对象,那么它将忽略这个事件, 继续执行
event.isSet():返回event的状态值;
event.wait():如果 event.isSet()==False将阻塞线程;
event.set(): 设置event的状态值为True,所有阻塞池的线程激活进入就绪状态, 等待操作系统调度;
event.clear():恢复event的状态值为False。
#先检查mysql,mysql状态正确无误后再允许链接
from threading import Thread,Event
import threading
import time,random
def conn_mysql():
count=1
while not event.is_set(): #event.is_set返回event的状态
if count >5:
raise TimeoutError('链接超时')
print('<%s>第%s次尝试链接'%(threading.current_thread().getName(),count))
event.wait(0.5) #如果event.is_set()为FALSE则线程阻塞
count+=1
print('<%s>链接成功' %threading.current_thread().getName())
def check_mysql():
print(' %s正在检查mysql' %threading.current_thread().getName())
time.sleep(random.randint(1,2))
event.set() #设置event的状态为True
if __name__=='__main__':
event=Event()
conn1=Thread(target=conn_mysql)
conn2=Thread(target=conn_mysql)
check=Thread(target=check_mysql)
conn2.start()
check.start()
结果:
<Thread-2>第1次尝试链接
Thread-3正在检查mysql
<Thread-2>第2次尝试链接
<Thread-2>第3次尝试链接
<Thread-2>链接成功
- 条件Condition
1、使得线程等待,只有满足条件时,才释放n个线程
2、线程进行交互:一个线程用于修改这个变量使其满足其它线程继续往下执行的条件,其它线程则接收条件已经发生改变的信号。
3、条件变量是thread库提供的一种用于等待的同步机制,可以实现线程间的通信,它必须与互斥量配合使用,等待另一个线程中某个事件的发生(满足某个条件),然后线程才能继续执行 - 定时器
指定n秒后执行某操作
from threading import Timer
def hello():
print("hello, world")
t = Timer(1, hello)
t.start() # after 1 seconds, "hello, world" will be printed
验证码定时器
"""
#验证码,计时器:隔指定时间后执行某任务
from threading import Timer
import random
class Code:
def __init__(self):
self.make_cache()
def make_cache(self,interval=5):
self.cache=self.make_code()
print(self.cache)
self.t=Timer(interval,self.make_cache)
self.t.start() #计时开始
def make_code(self,n=4):
res=''
for i in range(n):
s1=str(random.randint(0,9))
s2=chr(random.randint(65,90))
res+=random.choice([s1,s2])
return res
def check(self):
while True:
print('请输入验证码:')
inp=input('>>:').strip()
if inp.upper()==self.cache:
print('验证成功',end='\n')
self.t.cancel()
break
if __name__=='__main__':
obj=Code()
obj.check()
运行结果:
7739
请输入验证码:
>>:7739
验证成功