import threadingdef showa():
while True:
lockc.acquire()# 获取对方的锁,释放自己的锁
print('a', end='')
locka.release()def showb():
while True:
locka.acquire()
print('b', end='')
lockb.release()
# time.sleep(0.2)def showc():
while True:
lockb.acquire()
print('c', end='')
# sys.stdout.flush()
lockc.release()
# time.sleep(0.2)if __name__ == '__main__':
locka = threading.Lock()# 定义3个互斥锁
lockb = threading.Lock()
lockc = threading.Lock()t1 = threading.Thread(target=showa)# 定义3个线程
t2 = threading.Thread(target=showb)
t3 = threading.Thread(target=showc)locka.acquire()# 先锁住a,b锁,保证先打印a
lockb.acquire()t1.start()
t2.start()
t3.start()
简单说明:
locka.acquire()
lockb.acquire()
先是a和b锁着故t2、t3线程无法拿到 a和b的锁所以无法执行打印 ; 此时c没有加锁, 故t1执行时可以获取到c锁,故先打印a(t1执行).
【Python-线程-循环顺序打印abc】t1执行完之后是b和c锁着,a没有锁,故可以执行t2了
推荐阅读
- 推荐系统论文进阶|CTR预估 论文精读(十一)--Deep Interest Evolution Network(DIEN)
- Python专栏|数据分析的常规流程
- Python|Win10下 Python开发环境搭建(PyCharm + Anaconda) && 环境变量配置 && 常用工具安装配置
- Python绘制小红花
- Pytorch学习|sklearn-SVM 模型保存、交叉验证与网格搜索
- OpenCV|OpenCV-Python实战(18)——深度学习简介与入门示例
- python|8. 文件系统——文件的删除、移动、复制过程以及链接文件
- 爬虫|若想拿下爬虫大单,怎能不会逆向爬虫,价值过万的逆向爬虫教程限时分享
- 分布式|《Python3网络爬虫开发实战(第二版)》内容介绍
- java|微软认真聆听了开源 .NET 开发社区的炮轰( 通过CLI 支持 Hot Reload 功能)