尽管您不应该直接使用2682433407422022039041,但是您应该能够安全地将asyncio和aioprocessing结合在一起。 Event(以及任何其他基于事件循环的异步框架)的主要缺点是阻塞了事件循环。 如果您尝试直接使用2682433407422039039043,则无论何时阻塞等待子进程,都将阻塞事件循环。 显然,这很糟糕。
避免这种情况的最简单方法是使用2682433407422022039040执行2682433407422022039040中的函数。2682433407422039039040是使用2682433407422039039041实现的进程池,但是2682433407422039039042内置支持在其中执行功能而不会阻塞事件循环。 这是一个简单的例子:
import time
import asyncio
from concurrent.futures import ProcessPoolExecutor
def blocking_func(x):
time.sleep(x) # Pretend this is expensive calculations
return x * 5
@asyncio.coroutine
def main():
#pool = multiprocessing.Pool()
#out = pool.apply(blocking_func, args=(10,)) # This blocks the event loop.
executor = ProcessPoolExecutor()
out = yield from loop.run_in_executor(executor, blocking_func, 10) # This does not
print(out)
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
对于大多数情况,仅此功能就足够了。 如果您发现自己需要来自2682433407422022039040的其他构造(如Queue、Event、Manager等),则有一个名为aioprocessing的第三方库(完整披露:我已经写过),该库提供所有2682433407422039039044兼容版本的2682433407422039039044数据结构。 。 这是一个演示示例:
import time
import asyncio
import aioprocessing
import multiprocessing
def func(queue, event, lock, items):
with lock:
event.set()
for item in items:
time.sleep(3)
queue.put(item+5)
queue.close()
@asyncio.coroutine
def example(queue, event, lock):
l = [1,2,3,4,5]
p = aioprocessing.AioProcess(target=func, args=(queue, event, lock, l))
p.start()
while True:
result = yield from queue.coro_get()
if result is None:
break
print("Got result {}".format(result))
yield from p.coro_join()
@asyncio.coroutine
def example2(queue, event, lock):
yield from event.coro_wait()
with (yield from lock):
yield from queue.coro_put(78)
yield from queue.coro_put(None) # Shut down the worker
if __name__ == "__main__":
loop = asyncio.get_event_loop()
queue = aioprocessing.AioQueue()
lock = aioprocessing.AioLock()
event = aioprocessing.AioEvent()
tasks = [
asyncio.async(example(queue, event, lock)),
asyncio.async(example2(queue, event, lock)),
]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()