线程锁相当于同时只能有一个线程申请锁,有的场景无数据修改互斥要求可以同时让多个线程同时运行,且需要限制并发线程数量时可以使用信号量
import threading, time, queue def test(name): semaphore.acquire() #获取信号量锁 print('my name is %s' %name) time.sleep(1) semaphore.release() #释放信号量锁 semaphore = threading.BoundedSemaphore(5) #创建一个信号量同时可以运行3个线程 for i in range(20): t = threading.Thread(target=test, args=(i,)) t.start() while threading.active_count() == 1: print("all run done")
两个或者多个线程需要交互时,且一个进程需要根据另一线程状态执行对应操作时,可以通过event来设置线程状态达到期望的效果,下面是一个红绿灯的例子
event = threading.Event() #实例化一个event def light(): while True: print("红灯亮了,请停车") time.sleep(20) #开始是红灯20s event.set() #红灯时间到了,设置标志位 print("绿灯亮了,请通行") time.sleep(30) #持续30s红灯 event.clear() #清空标志位 def car(num): while True: if event.is_set():#检测event被设置则执行 print("car %s run"%num) time.sleep(5) else: print("this is red light waiting") event.wait() #此处会卡主,直到状态被设置才会向下执行 Light = threading.Thread(target=light,) Light.start() for i in range(10): Car = threading.Thread(target=car, args=(i,)) Car.start()
当多个线程需要交互数据可以使用queue来进行数据传递,下面是经典的生产者消费者多线程模型示例,其中包含线程queue的基本使用方法
my_queue = queue.Queue() #实例化一个队列 queue1 = queue.LifoQueue() #后进 先出队列 queue2 = queue.PriorityQueue() #带优先级的队列 def pro(): for i in range(100): my_queue.put(i) #队列里面放数据 def con(): while my_queue.qsize() > 0: #当队列有数据时候从队列取数据 print("i an a consumer,get num %s"%my_queue.get(timeout=3)) time.sleep(2) else: print("my queue is empty") Pro = threading.Thread(target=pro) Pro.start() for j in range(10): Con = threading.Thread(target=con) Con.start()
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com
暂无评论...
更新日志
2024年09月27日
2024年09月27日
- 梁静茹.2007-崇拜【相信音乐】【WAV+CUE】
- 金佩姗.1997-喜新恋旧【现代派】【WAV+CUE】
- 梁静茹.2007-崇拜【相信音乐】【WAV+CUE】
- 陈晓东.1997-在乎你感受(EP)【宝丽金】【WAV+CUE】
- 纯音入心系列纯音乐《云水禅心 - 佛曲古筝礼赞1-2》1CD[MP3][190MB]
- 纯音入心系列纯音乐《精心传神-古筝》1CD[MP3][363.1MB]
- 纯音入心系列纯音乐《琴瑟古风之古筝精选曲》1CD[MP3][354.1MB]
- 陈晓东.1997-在乎你感受(EP)【宝丽金】【WAV+CUE】
- 黄凯芹.1990-给你留念(2024环球MQA-UHQCD限量版)【环球】【WAV+CUE】
- 张学友.1999-有个人【宝丽金】【WAV+CUE】
- 纯音入心系列纯音乐《古筝佛曲》1CD[MP3][411.1MB]
- 纯音入心系列纯音乐《古筝世界名曲》1CD[MP3][38.9MB]
- 纯音入心系列纯音乐《古筝新奏-菩提妙音》1CD[MP3][112.3MB]
- 陈思安.1993-怀念福建金曲5CD【歌丽美】【WAV+CUE】
- 张学友.1999-有个人【宝丽金】【WAV+CUE】