【问题标题】:Add multithreading layer to Asyncio将多线程层添加到 Asyncio
【发布时间】: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


【解决方案1】:

根据要求,您的代码修改为使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-09
    • 2014-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-25
    相关资源
    最近更新 更多