我有两个独立的生成器(实际上它们由两个独立的零 mq 订阅者提供)。
我想从同一个事件循环中使用它们。
像这样概念上:
import time
def gen_one():
while True:
yield 1
time.sleep(1)
def gen_two():
while True:
yield 2
time.sleep(1.3)
for a in gen_one() or gen_two():
print a
# would like to see:
# 1
# 2
# 1
# 2
# 1
# 2
# 1
# 1
# 2
# ...
请注意,这是在 Python 2.7 中。
现在我显然得到 1,1,1,1...
我可以以某种方式将第二个迭代器嵌套到第一个迭代器中(不是循环,而是检查是否有要读取的内容),但充其量只能将内部消费者的速率限制为外部消费者的速率,这是不可取的。
请注意,zip() 不是一个好的选择,原因与上面提到的相同,此外还强制两个生成器具有相同的速率,而它们却没有。
关于如何实现这一点有什么建议吗?
根据评论中的建议,这样的事情可能会奏效:
from multiprocessing import Process, Queue
import time
def gen_one(queue):
while True:
queue.put(1)
time.sleep(1)
def gen_two(queue):
while True:
queue.put(2)
time.sleep(1.3)
queue = Queue()
p1 = Process(target=gen_one, args=(queue,)).start()
p2 = Process(target=gen_two, args=(queue,)).start()
while True:
a = queue.get()
print a
完成工作。
虽然没有我想要的那么直接或优雅,但绝对不糟糕。
请您参考如下方法:
所有生成器是否可以简单地将它们的产品推送到一个联合队列中,而主线程只获取队列中的任何内容?
import queue
import threading
q = queue.Queue()
def gen_one():
while True:
# yield 1
q.put(1)
time.sleep(1)
def gen_two():
while True:
# yield 2
q.put(2)
time.sleep(1.3)
def main():
while True:
x = q.get(block=True) # block to yield thread
print(x)
threading.Thread(target=gen_two, daemon=True).start()
threading.Thread(target=gen_one, daemon=True).start()
m = threading.Thread(target=main, daemon=True)
m.start()
m.join()
输出类似于2 1 1 2 1 2 1 2 1 1 2 1
您可以将“产生”功能包装到“放置”功能中。如果您确实关心产品的来源,请在将对象放入队列时添加标签。
