一 概念
Queue.task_done() 在完成一项工作之后,Queue.task_done()函数向任务已经完成的队列发送一个信号
Queue.join() 实际上意味着等到队列为空,再执行别的操作。
二 实例
源码一
import threading import queue import time # 创建队列,用于存储数据 q = queue.Queue() icnt = 0 def producer(): while True: global icnt icnt = icnt + 1 #print("producer icnt is:%d "%icnt) data = "hello world" print("producer is:",icnt) q.put(data) # 生产者线程函数,向队列存入数据 #q.join() data = "hello queue aaa " print("producer is:aaa ",icnt) q.put(data) # 生产者线程函数,向队列存入数据 q.join() time.sleep(1) def consumer(): while True: data = q.get() # 消费者线程,从队列取出数据 q.task_done() print("consumer is:",data) # 创建并启动生产者、消费者线程 t1 = threading.Thread(target=producer) t2 = threading.Thread(target=consumer) t1.start() t2.start() # 等待线程结束 t1.join() t2.join()
运行结果:
producer is: 1 producer is:aaa 1 consumer is: hello world consumer is: hello queue aaa producer is: 2 producer is:aaa 2 consumer is: hello world consumer is: hello queue aaa
源码二
import threading import queue import time # 创建队列,用于存储数据 q = queue.Queue() icnt = 0 def producer(): while True: global icnt icnt = icnt + 1 #print("producer icnt is:%d "%icnt) data = "hello world" print("producer is:",icnt) q.put(data) # 生产者线程函数,向队列存入数据 q.join() data = "hello queue aaa " print("producer is:aaa ",icnt) q.put(data) # 生产者线程函数,向队列存入数据 q.join() time.sleep(1) def consumer(): while True: data = q.get() # 消费者线程,从队列取出数据 q.task_done() print("consumer is:",data) # 创建并启动生产者、消费者线程 t1 = threading.Thread(target=producer) t2 = threading.Thread(target=consumer) t1.start() t2.start() # 等待线程结束 t1.join() t2.join()
运行结果:
producer is: 1 consumer is: hello world producer is:aaa 1 consumer is: hello queue aaa producer is: 2 consumer is: hello world producer is:aaa 2 consumer is: hello queue aaa
三 总结
看完例子,再回头看刚开始的那段话,会有豁然开朗的感觉。
Queue.task_done() 在完成一项工作之后,Queue.task_done()函数向任务已经完成的队列发送一个信号
Queue.join() 实际上意味着等到队列为空,再执行别的操作。
作者:虚生 出处:https://www.cnblogs.com/dylancao/ 以音频和传感器算法为核心的智能可穿戴产品解决方案提供商 ,提供可穿戴智能软硬件解决方案的设计,开发和咨询服务。 勾搭热线:邮箱:1173496664@qq.com weixin:18019245820 市场技术对接群:347609188 |
![]() |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
2018-10-08 hdf 5文件格式及python中利用h5py模块读写h5文件