【发布时间】:2021-09-17 10:40:29
【问题描述】:
我目前使用 AsyncIO 可以正常运行这段代码。
async def main():
while(1):
loop.create_task(startAsyncJob())
await asyncio.sleep(1)
async def startAsyncJob():
#myCodeHere
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
我尝试添加一个多线程层,这样我就可以同时运行我的“main”中的多个部分。所以我提取了它的代码,把它放在它自己的函数AsyncJobThread 中,我使用线程通过我的新主函数启动它:
def main():
try:
_thread.start_new_thread( AsyncJobThread, (1))
_thread.start_new_thread( AsyncJobThread, (15))
except:
print ("Error: unable to start thread")
async def AsyncJobThread(frequence):
while(1):
loop.create_task(startAsyncJob())
await asyncio.sleep(frequence)
async def startAsyncJob():
#myCodeHere
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
但是当前的实现给了我以下错误:
sys:1: RuntimeWarning: coroutine 'AsyncJobThread' was never awaited
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
【问题讨论】:
-
你不能像那样混合线程和异步。你需要在每个线程中运行一个新的事件循环。为什么不使用类似
asyncio.gather的东西同时运行多个东西呢? -
从来没用过这样的东西,其实我昨天才开始用asyncio。您能否详细说明您将如何使用
asyncio.gather在答案中做到这一点? -
@dirn 谢谢我刚刚尝试为每个线程使用一个新的事件循环并且它工作了。
-
附带说明,没有理由使用
_thread代替threading.Thread。 (或者,可能有,但你真的需要知道你在做什么)。作为经验法则,如果在 Python 中以_开头,则不应直接使用它(它相当于其他语言中的“私有”变量)
标签: python python-3.x multithreading python-asyncio