为 Asyncio 添加多线程层

Add multithreading layer to Asyncio

我目前有这段代码 运行使用 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())

我尝试添加一个多线程层,这样我就可以 运行 同时处理“主”中的多个部分。所以我提取了它的代码,把它放在我自己的函数 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

async def main():
    await asyncio.gather(
        AsyncJobThread(1),
        AsyncJobThread(15),
    )

async def AsyncJobThread(frequence):
    loop = asyncio.get_event_loop()
    while True:
        loop.create_task(startAsyncJob())
        await asyncio.sleep(frequence)


async def startAsyncJob():
    #myCodeHere

asyncio.run(main())

如果愿意,您还可以获得循环的引用并将其传递给 AsyncJobThread