【问题标题】:Start an async function inside a new thread在新线程中启动异步函数
【发布时间】:2020-07-23 20:04:26
【问题描述】:

我正在尝试创建一个不和谐机器人,我需要在另一个新线程中运行一个异步函数,因为主线程需要运行另一个函数(不和谐客户端)

我想要完成的事情:

# This methods needs to run in another thread
async def discord_async_method():
    while True:
        sleep(10)
        print("Hello World")
        ... # Discord Async Logic

# This needs to run in the main thread
client.run(TOKEN)

thread = ""

try:
    # This does not work, throws error "printHelloWorld Needs to be awaited"
    thread = Thread(target=discord_async_method)
    thread.start()
except (KeyboardInterrupt, SystemExit):

    # Stop Thread when CTRL + C is pressed or when program is exited
    thread.join()

我已尝试使用 asyncio 的其他解决方案,但我无法让其他解决方案发挥作用。

跟进:当你创建一个线程时,当你停止程序时如何停止该线程,即 KeyboardInterupt 或 SystemExit?

任何帮助将不胜感激,谢谢!

【问题讨论】:

    标签: python python-3.x multithreading async-await python-asyncio


    【解决方案1】:

    您不需要让线程在 asyncio 中并行运行两件事。只需在启动客户端之前将协程作为任务提交到事件循环。

    注意你的协程不能运行阻塞调用,所以你需要等待asyncio.sleep()而不是调用sleep()。 (这通常是协程的情况,而不仅仅是不和谐的。)

    async def discord_async_method():
        while True:
            await asyncio.sleep(10)
            print("Hello World")
            ... # Discord Async Logic
    
    # run discord_async_method() in the "background"
    asyncio.get_event_loop().create_task(discord_async_method())
    
    client.run(TOKEN)
    

    【讨论】:

    • 如果您需要在后台或并行进行阻塞调用,您是否需要使用多处理?
    • @WaqasAbbasi 不需要多处理,线程就足够了(而且更轻量级)。 Asyncio 提供了一个方便的函数run_in_executor,正是为了在不阻塞事件循环的情况下从异步函数运行遗留阻塞代码(或 CPU 绑定代码)。
    【解决方案2】:

    这也适用于我:

    def entrypoint(*params):
        asyncio.run(discord_async_method(*params))
    
    t = threading.Thread(target=entrypoint, args=(param,), daemon=True)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-22
      • 2023-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多