close

How do I pass an async function to a thread target in Python?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How do I pass an async function to a thread target in Python in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How do I pass an async function to a thread target in Python?

  1. How do I pass an async function to a thread target in Python?

    As of Python 3.7, you can use asyncio.run() which is a bit more straightforward than loop.run_until_complete():

  2. I pass an async function to a thread target in Python

    As of Python 3.7, you can use asyncio.run() which is a bit more straightforward than loop.run_until_complete():

Method 1

You can do it by adding function between to execute async:

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()

Method 2

As of Python 3.7, you can use asyncio.run() which is a bit more straightforward than loop.run_until_complete():

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

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read