我有很少的阻止功能foo,bar我无法改变那些(一些我无法控制的内部库.与一个或多个网络服务交谈).我如何将其用作异步?我不想做以下事情.
results = []
for inp in inps:
val = foo(inp)
result = bar(val)
results.append(result)
Run Code Online (Sandbox Code Playgroud)
这将是低效的,因为我foo在等待第一个输入时可以调用第二个输入,并且相同bar.如何包装它们,这样它们与ASYNCIO(即新的使用async,await语法)?
让我们假设这些函数是可重入的.即,foo当先前foo正在处理时再次调用是可以的.
更新
用可重复使用的装饰器扩展答案.点击这里举例.
def run_in_executor(f):
@functools.wraps(f)
def inner(*args, **kwargs):
loop = asyncio.get_running_loop()
return loop.run_in_executor(None, functools.partial(f, *args, **kwargs))
return inner
Run Code Online (Sandbox Code Playgroud) 这个问题不同于Is there a way to use asyncio.Queue in multiple thread?
我有 2 个异步事件循环在两个不同的线程中运行。Thread1 通过asyncio.Queue()向 Thread2 生成数据。
其中一个线程抛出异常:got Future <Future pending> attached to a different loop
现在这是真的,因为我有一个在不同循环中使用的队列。如何在两个不同线程中的两个循环之间共享队列?
示例代码:
q = asyncio.Queue()
async def producer(q):
await asyncio.sleep(3)
q.put(1)
def prod_work(q):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(producer(q))
async def consumer(q):
await asyncio.sleep(3)
res = await q.get()
def cons_work(q):
loop2 = asyncio.new_event_loop()
asyncio.set_event_loop(loop2)
loop2.run_until_complete(consumer(q))
def worker(q):
# main thread - uses this threads loop
prod = threading.Thread(target=prod_work, args=(q,))
# separate …Run Code Online (Sandbox Code Playgroud)