python3 queue多线程通信
作者:lilongsy??????? 发布时间:2022-09-20 08:41:05
标签:python,queue,多线程,通信
queue分类
python3 queue分三类:
先进先出队列
后进先出的栈
优先级队列
他们的导入方式分别是:
from queue import Queue
from queue import LifoQueue
from queue import
具体方法见下面引用说明。
例子一、生产消费模式
Queue
对象已经包含了必要的锁,所以你可以通过它在多个线程间多安全地共享数据。 当使用队列时,协调生产者和消费者的关闭问题可能会有一些麻烦。一个通用的解决方法是在队列中放置一个特殊的值,当消费者读到这个值的时候,终止执行。
例如:
from queue import Queue
from threading import Thread
# 用来表示终止的特殊对象
_sentinel = object()
# A thread that produces data
def producer(out_q):
for i in range(10):
print("生产")
out_q.put(i)
out_q.put(_sentinel)
# A thread that consumes data
def consumer(in_q):
while True:
data = in_q.get()
if data is _sentinel:
in_q.put(_sentinel)
break
else:
print("消费", data)
# Create the shared queue and launch both threads
q = Queue()
t1 = Thread(target=consumer, args=(q,))
t2 = Thread(target=producer, args=(q,))
t1.start()
t2.start()
结果:
本例中有一个特殊的地方:消费者在读到这个特殊值之后立即又把它放回到队列中,将之传递下去。这样,所有监听这个队列的消费者线程就可以全部关闭了。 尽管队列是最常见的线程间通信机制,但是仍然可以自己通过创建自己的数据结构并添加所需的锁和同步机制来实现线程间通信。最常见的方法是使用 Condition
变量来包装你的数据结构。下边这个例子演示了如何创建一个线程安全的优先级队列。
import heapq
import threading
class PriorityQueue:
def __init__(self):
self._queue = []
self._count = 0
self._cv = threading.Condition()
def put(self, item, priority):
with self._cv:
heapq.heappush(self._queue, (-priority, self._count, item))
self._count += 1
self._cv.notify()
def get(self):
with self._cv:
while len(self._queue) == 0:
self._cv.wait()
return heapq.heappop(self._queue)[-1]
例子二、task_done和join
使用队列来进行线程间通信是一个单向、不确定的过程。通常情况下,你没有办法知道接收数据的线程是什么时候接收到的数据并开始工作的。不过队列对象提供一些基本完成的特性,比如下边这个例子中的task_done()
和 join()
:
from queue import Queue
from threading import Thread
class Producer(Thread):
def __init__(self, q):
super().__init__()
self.count = 5
self.q = q
def run(self):
while self.count > 0:
print("生产")
if self.count == 1:
self.count -= 1
self.q.put(2)
else:
self.count -= 1
self.q.put(1)
class Consumer(Thread):
def __init__(self, q):
super().__init__()
self.q = q
def run(self):
while True:
print("消费")
data = self.q.get()
if data == 2:
print("stop because data=", data)
# 任务完成,从队列中清除一个元素
self.q.task_done()
break
else:
print("data is good,data=", data)
# 任务完成,从队列中清除一个元素
self.q.task_done()
def main():
q = Queue()
p = Producer(q)
c = Consumer(q)
p.setDaemon(True)
c.setDaemon(True)
p.start()
c.start()
# 等待队列清空
q.join()
print("queue is complete")
if __name__ == '__main__':
main()
结果:
例子三、多线程里用queue
设置俩队列,一个是要做的任务队列todo_queue
,一个是已经完成的队列done_queue
。
每次执行线程,先从todo_queue
队列里取出一个值,然后执行完,放入done_queue
队列。
如果todo_queue
为空,就退出。
import logging
import logging.handlers
import threading
import queue
log_mgr = None
todo_queue = queue.Queue()
done_queue = queue.Queue()
class LogMgr:
def __init__(self, logpath):
self.LOG = logging.getLogger('log')
loghd = logging.handlers.RotatingFileHandler(logpath, "a", 0, 1)
fmt = logging.Formatter("%(asctime)s %(threadName)-10s %(message)s", "%Y-%m-%d %H:%M:%S")
loghd.setFormatter(fmt)
self.LOG.addHandler(loghd)
self.LOG.setLevel(logging.INFO)
def info(self, msg):
if self.LOG is not None:
self.LOG.info(msg)
class Worker(threading.Thread):
global log_mgr
def __init__(self, name):
threading.Thread.__init__(self)
self.name = name
def run(self):
while True:
try:
task = todo_queue.get(False)
if task:
log_mgr.info("HANDLE_TASK: %s" % task)
done_queue.put(1)
except queue.Empty:
break
return
def main():
global log_mgr
log_mgr = LogMgr("mylog")
for i in range(30):
todo_queue.put("data"+str(i))
workers = []
for i in range(3):
w = Worker("worker"+str(i))
workers.append(w)
for i in range(3):
workers[i].start()
for i in range(3):
workers[i].join()
total_num = done_queue.qsize()
log_mgr.info("TOTAL_HANDLE_TASK: %d" % total_num)
exit(0)
if __name__ == '__main__':
main()
输出日志文件结果:
来源:https://blog.51cto.com/lilongsy/5454381
0
投稿
猜你喜欢
- 围绕文字、符号、链接三个方面,主要是中文,草拟的个人行文经验:1. 文字避免写错。应付挑剔的读者是一个方面,某些关键词的错误,有可能就避过了
- Python 面向对象方法没有重载#在其他语言中,可以定义多个重名的方法,只要保证方法签名唯一即可。方法签名包含3个部分:方法名、参数数量、
- 前言复习试题时,发现一道复数问题问题关于 Python 的复数类型,以下选项中描述错误的是A复数的虚数部分通过后缀“J”或者“j”来表示B对
- 在Python探索之SocketServer详解中我们介绍了Python标准库中的SocketServer模块,了解了要实现网络通信服务,就
- Matplotlib效果图如下主要使用matplotlib.animation.FuncAnimation,上核心代码,# 定义静态绘图函数
- 代码如下:---1.平均销售等待时间 ---有一张Sales表,其中有销售日期与顾客两列,现在要求使用一条SQL语句实现计算 --每个顾客的
- Sun周三宣布,准备以10亿美元收购MySQL开源数据库公司。据悉,Sun将支付大约8亿美元现金给MySQL,以获得其私募股票,另外,Sun
- 目录最终版本过程借鉴代码思考urllib.request和requestsBeautifulSoup优化处理总结代码复制可直接使用,记得pi
- 今天主要向大家讲述的是优化SQL Server数据库的实际操作经验的总结,同时也有对其优化的实际操作中出现的一些问题的描述,以及对SQL S
- MATLAB转格式,需要使用spm package(https://github.com/neurodebian/spm12).%%img2
- 如果你想把Python嵌入C/C++中是比较简单的事情,你需要的是在VC中添加Python的include文件目录和lib文件目录。下面我们
- 题记JS中的this指向一直是个让初学者头疼的问题。今天,我们就一起来瞅瞅this倒地是咋回事,详细说说this指向原则,从此不再为了thi
- 前言matplotlib是基于Python语言的开源项目,旨在为Python提供一个数据绘图包。在使用Python matplotlib库绘
- 如果你在 ForeignKey或 ManyToManyField字段上使用 related_name属性,你必须总是为该字段指定一个唯一的反
- 技巧1XmlNode.InnerText与.InnerXml的区别是:前者将内容中的<和>分别变成<和>,因此,希望
- 一、安装写出许多有趣的可视化东西也可以画出很多奇妙的图案pip install turtule二、画布画布就是turtle为我们展开用于绘图
- 编写Python SDK代码工程目录结构├──── easyhttp
- 作为临时测试用python命令来搭建web测试是最好不过的选择了;CD切换到当前目录只需要一句python命令就迅速搭建好了简单的web服务
- 条形图(bar chart),也称为柱状图,是一种以长方形的长度为变量的统计图表,长方形的长度与它所对应的变量数值呈一定比例。1. 竖放条形
- 直接上代码:<span style="font-family: arial,helvetica,sans-serif; fo