Python互斥锁实例(包含超时解锁)
文章目录
- 前言
- 正文
- 1 锁被占用直接返回
- 2 拿不到锁则一直等待
- 3 拿不到锁等待直到超时
- 总结
前言
最近遇到一个小需求,大概是请求机器人&自动化设备执行某些功能,这些功能之间有共同操作资源或在业务逻辑上有冲突,如何保证多线程的请求不会同时执行造成损失。1
这里使用的是互斥锁,当有任务正在执行时写了如下几种处理方式:
- 直接返回
- 等待拿到锁,继续执行
- 等待拿到锁,继续执行或超时返回
正文
代码如下:
import threading
import timeprocess_lock = threading.Lock()def process1(id_num):name = 'process1-' + str(id_num)if process_lock.locked():print(name, ' is locked')returnif process_lock.acquire():time.sleep(0.1)print(name, ' get lock ')process_lock.release()print(name, ' release lock')def process2(id_num):name = 'process2-' + str(id_num)if process_lock.locked():print(name, ' is locked')if process_lock.acquire():time.sleep(0.2)print(name, ' get lock ')process_lock.release()print(name, ' release lock')def process3(id_num):name = 'process3-'+str(id_num)if process_lock.locked():print(name, ' is locked')if process_lock.acquire(blocking=True, timeout=0.3):try:print(name, ' get lock')time.sleep(0.2)finally:process_lock.release()print(name, ' release lock')if __name__ == '__main__':# # 如果锁被占用则直接返回# for i in range(3):# threading.Thread(target=process1, args=(i,)).start()# # 如果拿不到锁则一直等待# for i in range(3):# time.sleep(0.1)# threading.Thread(target=process2, args=(i,)).start()# 如果拿不到锁则等待,直到超时for i in range(3):threading.Thread(target=process3, args=(i,)).start()
1 锁被占用直接返回
process1-1 is locked
process1-2 is locked
process1-0 get lock
process1-0 release lock
0号线程拿到了锁,1 2线程没拿到锁直接返回
2 拿不到锁则一直等待
process2-1 is locked
process2-0 get lock
process2-0 release lock
process2-2 is locked
process2-1 get lock
process2-1 release lock
process2-2 get lock
process2-2 release lock
0 1 2三个线程逐次拿到锁,执行后释放
3 拿不到锁等待直到超时
process3-0 get lock
process3-1 is locked
process3-2 is locked
process3-0 release lock
process3-1 get lock
process3-1 release lock
0 拿到锁执行完释放,2拿到锁再释放,于此同时3已经超时
总结
虽然这篇文章写的比较基础,但是实际使用中大家可能都会用的到,整理记录于此。
threading — Thread-based parallelism — Python 3.12.2 documentation ↩︎