Vi.*_*Vi. 7 python generator python-2.7
请考虑以下伪代码:
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() )
Run Code Online (Sandbox Code Playgroud)
如何以最简单的方式实现这一点?
看起来就像有人已经实现了这个: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
Run Code Online (Sandbox Code Playgroud)