如何在Python中将异步函数传递给线程目标?

时间:2020-01-08 11:51:01

标签: python multithreading

我有以下代码:

async some_callback(args):
    await some_function()

,我需要将其作为目标提供给线程:

_thread = threading.Thread(target=some_callback, args=("some text"))
_thread.start()

问题是我收到从未等待“ some_callback”的错误。有什么想法可以解决这个问题吗?

2 个答案:

答案 0 :(得分:3)

您可以通过在之间添加功能来执行异步来做到这一点:

async def some_callback(args):
    await some_function()

def between_callback(args):
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)

    loop.run_until_complete(some_callback(args))
    loop.close()

_thread = threading.Thread(target=between_callback, args=("some text"))
_thread.start()

答案 1 :(得分:3)

从Python 3.7开始,您可以使用asyncio.run(),它比loop.run_until_complete()更加简单:

_thread = threading.Thread(target=asyncio.run, args=(some_callback("some text"),))
_thread.start()