# 死锁现象是怎么产生的?
# 多把(互斥/递归)锁 并且在多个线程中 交叉使用
# fork_lock.acquire()
# noodle_lock.acquire()
#
# fork_lock.release()
# noodle_lock.release()
# 如果是互斥锁,出现了死锁现象,最快速的解决方案把所有的互斥锁都改成一把递归锁
# 程序的效率会降低的
# 递归锁 效率低 但是解决死锁现象有奇效
# 互斥锁 效率高 但是多把锁容易出现死锁现象
# 一把互斥锁就够了
from threading import Lock,RLock # Lock 互斥锁 效率高 # RLock 递归(recursion)锁 效率相对低 l = Lock() l.acquire() print('希望被锁住的代码') l.release() rl = RLock() # 在同一个线程中可以被acquire多次 rl.acquire() print('希望被锁住的代码') rl.release() from threading import Thread,RLock as Lock def func(i,lock): lock.acquire() lock.acquire() print(i,': start') lock.release() lock.release() print(i, ': end') lock = Lock() for i in range(5): Thread(target=func,args=(i,lock)).start()
队列
import queue # 线程之间数据安全的容器队列 from queue import Empty # 不是内置的错误类型,而是queue模块中的错误 q = queue.Queue(4) # fifo 先进先出的队列 q.get() q.put(1) q.put(2) q.put(3) q.put(4) print('4 done') q.put_nowait(5) print('5 done') try: q.get_nowait() except Empty:pass print('队列为空,继续其他内容') from queue import LifoQueue # last in first out 后进先出 栈 lq = LifoQueue() lq.put(1) lq.put(2) lq.put(3) print(lq.get()) print(lq.get()) print(lq.get()) from queue import PriorityQueue # 优先级队列 priq = PriorityQueue() priq.put((2,'alex')) priq.put((1,'wusir')) priq.put((0,'太白')) print(priq.get()) print(priq.get()) print(priq.get())
单例模式
import time class A: from threading import Lock __instance = None lock = Lock() def __new__(cls, *args, **kwargs): with cls.lock: if not cls.__instance: time.sleep(0.000001) # cpu轮转 cls.__instance = super().__new__(cls) return cls.__instance