Python并发与脚本编程实用技巧
1. 多线程队列轮询
在处理多线程队列时,我们常常会遇到需要同时从多个队列读取数据的情况。例如,在一个复杂的系统中,可能有多个生产者向不同的队列中放入数据,而我们需要一个消费者能够同时处理这些队列中的数据。
下面是一个使用 select 模块实现同时从多个队列读取数据的示例代码:
import select
import threading
def consumer(queues):
'''
Consumer that reads data on multiple queues simultaneously
'''
while True:
can_read, _, _ = select.select(queues, [], [])
for r in can_read:
item = r.get()
print('Got:', item)
q1 = PollableQueue()
q2 = PollableQueue()
q3 = PollableQueue()
t = threading.Thread(target=consumer, args=([q1, q2, q3],))
t.daemon = True
t.start()
# Feed data to the queues
q1.put(1)
q2.put(10)
q3.put('hello')
q2.put(15)
运行上述代码,消费者将能够
订阅专栏 解锁全文
407




被折叠的 条评论
为什么被折叠?



