DEV Community

Muhammad Atif Iqbal
Muhammad Atif Iqbal

Posted on

What is threading in Python?

🔹 What is threading in Python?

  • Threading means running multiple threads of execution within the same process.
  • A thread is the smallest unit of a program that can run independently.
  • In Python, threads are often used for tasks like:

    • Handling multiple user requests in a web server.
    • Running background tasks (like sending emails, logging, or processing data).
    • Improving responsiveness (so the program doesn’t “freeze” while waiting for something).

👉 Example:

import threading
import time

def worker(name):
    print(f"{name} started")
    time.sleep(2)
    print(f"{name} finished")

# Create 2 threads
t1 = threading.Thread(target=worker, args=("Thread-1",))
t2 = threading.Thread(target=worker, args=("Thread-2",))

t1.start()
t2.start()
Enter fullscreen mode Exit fullscreen mode

This runs two “workers” at the same time (interleaved).


🔹 Why use threading in Django?

  • Django (and many web servers like Gunicorn or Uvicorn) may serve multiple users at once.
  • Each request may be handled by a different thread.
  • If you need some data specific to a request/thread (like which website/domain is being used), you can store it in thread-local storage so that it doesn’t get mixed up with another request.

🔹 What is _thread_local?

_thread_local = threading.local()
Enter fullscreen mode Exit fullscreen mode
  • threading.local() creates a thread-local storage object.
  • That means each thread can store its own attributes without interfering with other threads.
  • _thread_local is just a variable name (the underscore _ is a Python convention meaning “this is private, internal use”).

👉 Example:

import threading

local_data = threading.local()

def worker(name):
    local_data.value = name
    print(f"In {name}, local_data.value = {local_data.value}")

t1 = threading.Thread(target=worker, args=("Thread-1",))
t2 = threading.Thread(target=worker, args=("Thread-2",))

t1.start()
t2.start()
Enter fullscreen mode Exit fullscreen mode

Each thread has its own local_data.value → no conflict.


âś… Summary in plain words:

  • Threading = running multiple requests at once.
  • threading.local() = keeps request-specific data separate.
  • _thread_local.current_website = acts like a per-request global variable.
  • Underscore _ = naming convention meaning “internal use only”.

Top comments (0)