可以用Python3吗asyncio
封装有Boost.Python
图书馆?
I have CPython
C++
构建的扩展Boost.Python
。以及编写的函数C++
可以工作很长时间。我想用asyncio
调用这些函数但是res = await cpp_function()
代码不起作用。
- 当发生什么
cpp_function
被称为内部协程?
- 怎样打电话才不会被屏蔽
C++
工作时间很长的功能?
NOTE: C++
不做一些I/O操作,只是计算。
当在协程内部调用 cpp_function 时会发生什么?
如果您在任何协程中调用长时间运行的 Python/C 函数,它会冻结您的事件循环(冻结所有协程)。
你应该避免这种情况。
如何不因调用运行时间很长的 C++ 函数而被阻塞
你应该使用在执行器中运行 https://docs.python.org/3/library/asyncio-eventloop.html#executor在单独的线程或进程中运行您的函数。run_in_executor
返回您可以等待的协程。
你可能需要ProcessPoolExecutor
因为 GIL (我不确定是否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()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)