Learn Python
>>> advanced_python.multithreading

Multithreading in Python

#concept

Multithreading runs several threads within one program at the same time, sharing the same memory space, useful for tasks that spend most of their time waiting — like network requests or file I/O — rather than doing constant CPU work. Python's Global Interpreter Lock (GIL) means only one thread actually executes Python bytecode at any single instant, so threads help with waiting-heavy tasks, but don't speed up CPU-bound calculations the way they might in some other languages.

#how it works
1

import threading

Brings in the module, part of the standard library.

2

Thread(target=function)

Creates a new thread that will run function.

3

.start() begins running it

Concurrently with the rest of the program.

4

.join() waits for it to finish

Pauses the calling code until that specific thread has fully completed.

5

The GIL shapes what threads are good for

Suiting I/O-bound waiting far better than CPU-bound computation.

#example
import threading
import time
 
def worker(name):
print(f"{name} starting")
time.sleep(1)
print(f"{name} finished")
 
t1 = threading.Thread(target=worker, args=("Thread-1",))
t2 = threading.Thread(target=worker, args=("Thread-2",))
 
t1.start()
t2.start()
 
t1.join()
t2.join()
 
print("Both threads done")
Output
Thread-1 starting
Thread-2 starting
Thread-1 finished
Thread-2 finished
Both threads done
1t1.start() and t2.start() both begin running immediately, one right after the other, rather than waiting for the first to fully finish before starting the second.
2Both threads print their "starting" message right away, then each independently sleeps for one second, simulating waiting on something like a network response.
3t1.join() and t2.join() make the main program wait until both threads have genuinely finished before continuing.
4"Both threads done" only prints once both threads have completed, thanks to those two join() calls.
#use cases
Downloading multiple files or making several web requests concurrently, so waiting on one doesn't block the others
Keeping a user interface responsive while a background task (like saving a file) is still in progress
Handling multiple client connections at once in a simple server
Understanding why CPU-heavy work needs multiprocessing instead, covered next, due to the GIL

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Python yourself — building beats watching.