Sobes.tech
Junior — Middle

Is it possible to create new threads inside asynchronous functions in Python?

sobes.tech AI

Answer from AI

Yes, it is possible to create new threads inside asynchronous functions in Python. Async functions (async def) run within an event loop, but nothing prevents using the standard threading module to create threads.

This can be useful if you need to perform a blocking operation alongside asynchronous code.

Example:

import asyncio
import threading

async def async_function():
    def thread_task():
        print("Running in a separate thread")

    thread = threading.Thread(target=thread_task)
    thread.start()
    await asyncio.sleep(1)
    thread.join()

asyncio.run(async_function())

However, keep in mind that threads in Python are limited by the GIL, and for CPU-intensive tasks, it is better to use processes (multiprocessing). For I/O operations, asynchronous code is usually more efficient.