How many threads does asyncio use python ?

Mar 17, 2024 ยท 2 min read

Asyncio is a powerful framework in Python that enables writing asynchronous, non-blocking code. A key advantage of asyncio is that it uses a single-thread under the hood, yet can handle many tasks concurrently.

The Event Loop

The core of asyncio is the event loop. This loop runs in a single thread and handles all the asynchronous tasks and IO operations. So when you call asyncio.run(), it will start this event loop and execute the async coroutines within it.

import asyncio

async def main():
    print('hello')
    await asyncio.sleep(1)
    print('world')

asyncio.run(main())

So how does it process multiple things with one thread? The key is that asyncio uses cooperative multitasking. When an async function needs to wait for some IO or timer, it will yield control back to the event loop, allowing other tasks to run.

This makes asyncio very lightweight compared to using multi-threading or multi-processing.

Creating Additional Threads

The asyncio event loop runs in the main thread by default. You can also create additional threads manually and run tasks there.

thread = threading.Thread(target=other_func) 
thread.start()

But typically you want to offload CPU-bound work to a thread and keep async tasks inside the main event loop thread.

Key Takeaways

  • Asyncio uses an event loop in a single thread to execute all asynchronous code
  • It enables concurrency despite using one thread due to cooperative multitasking
  • You can manually create threads to run CPU-bound work
  • Avoid blocking the main event loop thread for best performance
  • Using asyncio single-threaded design with async/await syntax makes it easy to write high-performance concurrent programs in Python.

    Browse by tags:

    Browse by language:

    The easiest way to do Web Scraping

    Get HTML from any page with a simple API call. We handle proxy rotation, browser identities, automatic retries, CAPTCHAs, JavaScript rendering, etc automatically for you


    Try ProxiesAPI for free

    curl "http://api.proxiesapi.com/?key=API_KEY&url=https://example.com"

    <!doctype html>
    <html>
    <head>
        <title>Example Domain</title>
        <meta charset="utf-8" />
        <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
    ...

    X

    Don't leave just yet!

    Enter your email below to claim your free API key: