多线程(锁/可重入锁/线程同步)/ 分布式锁
import time import redis import threading # redis连接池 pool = redis.ConnectionPool(host='127.0.0.1', port=6379, decode_responses=True) r = redis.StrictRedis(connection_pool=pool) queue = [] # 普通锁,不允许一个线程内被多次acquire,会出现死锁 # lock = threading.Lock() # 可重入锁,允许一个线程内被多次acquire,acquire/release必须成对出现 lock = threading.RLock() product = None con = threading.Condition() def thread_lock_task(): # 线程锁 lock.acquire() queue.append(1) print('{} 获取锁 len(queue)={}'.format( threading.currentThread().name, len(queue) )) lock.release() def distributed_lock_task(): # redis提供分布式锁 with r.lock(name='queue', timeout=30, blocking_timeout=30): queue.append(1) print('{} 获取锁 len(queue)={}'.format( threading.currentThread().name, len(queue) )) def produce(): # 线程同步;生产者 global product if con.acquire(): while True: if product is None: print('produce') product = 'something' # con.notify() # 唤起一个挂起线程,不会释放占用锁 con.notify_all() # 唤起全部挂起线程,不会释放占用锁 con.wait() # 释放占用锁,当前线程被挂起,直到收到通知或超时 time.sleep(2) def consume(): # 线程同步;消费者 global product if con.acquire(): while True: if product is not None: print('comsume') product = None con.notify() con.wait() time.sleep(2) t1 = threading.Thread(target=produce) t2 = threading.Thread(target=consume) t1.start() t2.start()