在Python 2中循环两个异步生成器

时间:2018-03-29 05:08:14

标签: python python-2.7

我有两个独立的发电机(实际上它们由两个独立的零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

完成工作。

不像我喜欢的那样直接或优雅,但绝对不是很糟糕。

1 个答案:

答案 0 :(得分:1)

所有生成器是否可以简单地将他们的产品推送到一个联合队列中,而主线程只是获取队列中的任何内容?

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
你可以包装你的“屈服”'功能进入' put'功能。如果您关心产品的来源,请在将对象放入队列时添加标记。

相关问题