gpt4 book ai didi

python - 如何将多个阻塞 Python 生成器复用为一个?

转载 作者:太空狗 更新时间:2023-10-29 21:44:19 25 4
gpt4 key购买 nike

考虑以下伪代码:

def g_user():
while True:
yield read_user_input()

def g_socket():
while True:
yield read_socket_input()

def g_combined(gu, gs):
# should read user or socket input, whichever is available

while True:
sel = select(gu, gs)
if sel.contains(gu):
yield gu.next()
if sel.contains(gs):
yield gs.next()

gc = g_combined ( g_user(), g_socket() )

如何以最简单的方式实现它?

最佳答案

看起来有人已经实现了这个:http://www.dabeaz.com/generators/genmulti.py

镜像在这里:

import Queue, threading
def gen_multiplex(genlist):
item_q = Queue.Queue()
def run_one(source):
for item in source: item_q.put(item)

def run_all():
thrlist = []
for source in genlist:
t = threading.Thread(target=run_one,args=(source,))
t.start()
thrlist.append(t)
for t in thrlist: t.join()
item_q.put(StopIteration)

threading.Thread(target=run_all).start()
while True:
item = item_q.get()
if item is StopIteration: return
yield item

关于python - 如何将多个阻塞 Python 生成器复用为一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9186740/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com