Python3 多线程与互斥锁
2021/6/5 20:51:05
本文主要是介绍Python3 多线程与互斥锁,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
简单实现多线程
import threading import time def sing(sing): for i in range(5): print("---sing()---{}".format(sing)) time.sleep(1) def dance(dance): for i in range(5): print("---dance()---{}".format(dance)) time.sleep(1) def main(): t1 = threading.Thread(target=sing,args=("t1",)) t2 = threading.Thread(target=dance,args=("t2",)) t1.start() t2.start() if __name__ == "__main__": main()
多线程互斥锁
import threading import time A = 2 lock = threading.Lock() #创建一个互斥锁 def sing(sing): global A for i in range(500000): lock.acquire() #加锁 A += 1 lock.release() #解锁 print('{}:{}'.format(sing,i)) def dance(dance): global A for i in range(500000): lock.acquire() #加锁 A -= 1 lock.release() #解锁 print('{}:{}'.format(dance,i)) def main(): global A t1 = threading.Thread(target=sing,args=("t1",)) t2 = threading.Thread(target=dance,args=("t2",)) t1.start() t2.start() t1.join() t2.join() print(A) if __name__ == "__main__": main()
这篇关于Python3 多线程与互斥锁的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-12-20Python编程入门指南
- 2024-12-20Python编程基础与进阶
- 2024-12-19Python基础编程教程
- 2024-12-19python 文件的后缀名是什么 怎么运行一个python文件?-icode9专业技术文章分享
- 2024-12-19使用python 把docx转为pdf文件有哪些方法?-icode9专业技术文章分享
- 2024-12-19python怎么更换换pip的源镜像?-icode9专业技术文章分享
- 2024-12-19Python资料:新手入门的全面指南
- 2024-12-19Python股票自动化交易实战入门教程
- 2024-12-19Python股票自动化交易入门教程
- 2024-12-18Python量化入门教程:轻松掌握量化交易基础知识