如何将 asyncio 与 boost.python 一起使用?
how to use asyncio with boost.python?
是否可以将 Python3 asyncio
包与 Boost.Python
库一起使用?
我有 CPython
C++
使用 Boost.Python
构建的扩展。用 C++
编写的函数可以工作很长时间。我想使用 asyncio
来调用这些函数,但是 res = await cpp_function()
代码不起作用。
- 在协程中调用
cpp_function
会发生什么?
- 如何不通过调用运行很长时间的
C++
函数而被阻止?
注意:C++
不做一些I/O操作,只是计算。
What happens when cpp_function is called inside coroutine?
如果您在任何协同程序中调用 long-运行ning Python/C 函数,它会冻结您的事件循环(冻结所有协同程序)。
你应该避免这种情况。
How not get blocked by calling C++ function that works very long time
您应该使用 run_in_executor 到 运行 您在单独的线程或进程中运行。 run_in_executor
returns 您可以等待的协程。
由于 GIL,您可能需要 ProcessPoolExecutor
(我不确定 ThreadPoolExecutor
是否适合您的情况,但我建议您检查一下)。
这里是等待长运行宁代码的例子:
import asyncio
from concurrent.futures import ProcessPoolExecutor
import time
def blocking_function():
# Function with long-running C/Python code.
time.sleep(3)
return True
async def main():
# Await of executing in other process,
# it doesn't block your event loop:
loop = asyncio.get_event_loop()
res = await loop.run_in_executor(executor, blocking_function)
if __name__ == '__main__':
executor = ProcessPoolExecutor(max_workers=1) # Prepare your executor somewhere.
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
loop.run_until_complete(main())
finally:
loop.run_until_complete(loop.shutdown_asyncgens())
loop.close()
是否可以将 Python3 asyncio
包与 Boost.Python
库一起使用?
我有 CPython
C++
使用 Boost.Python
构建的扩展。用 C++
编写的函数可以工作很长时间。我想使用 asyncio
来调用这些函数,但是 res = await cpp_function()
代码不起作用。
- 在协程中调用
cpp_function
会发生什么? - 如何不通过调用运行很长时间的
C++
函数而被阻止?
注意:C++
不做一些I/O操作,只是计算。
What happens when cpp_function is called inside coroutine?
如果您在任何协同程序中调用 long-运行ning Python/C 函数,它会冻结您的事件循环(冻结所有协同程序)。
你应该避免这种情况。
How not get blocked by calling C++ function that works very long time
您应该使用 run_in_executor 到 运行 您在单独的线程或进程中运行。 run_in_executor
returns 您可以等待的协程。
由于 GIL,您可能需要 ProcessPoolExecutor
(我不确定 ThreadPoolExecutor
是否适合您的情况,但我建议您检查一下)。
这里是等待长运行宁代码的例子:
import asyncio
from concurrent.futures import ProcessPoolExecutor
import time
def blocking_function():
# Function with long-running C/Python code.
time.sleep(3)
return True
async def main():
# Await of executing in other process,
# it doesn't block your event loop:
loop = asyncio.get_event_loop()
res = await loop.run_in_executor(executor, blocking_function)
if __name__ == '__main__':
executor = ProcessPoolExecutor(max_workers=1) # Prepare your executor somewhere.
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
loop.run_until_complete(main())
finally:
loop.run_until_complete(loop.shutdown_asyncgens())
loop.close()