Lesson 43 of 55
PythonConcurrency with threading
20 minutes
Course progress78%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 43 of 55
Python20 minutes
Keep these ideas in mind as you work through the lesson.
The threading module lets you run multiple threads in the same process, which is handy for I/O‑bound tasks such as network requests or file operations.
import threading
import time
def worker(name):
print(f'Thread {name} starting')
time.sleep(2)
print(f'Thread {name} finished')
threads = []
for i in range(3):
t = threading.Thread(target=worker, args=(i,))
threads.append(t)
t.start()
# Wait for all threads to finish
for t in threads:
t.join()
print('All threads completed')
Because of the Global Interpreter Lock (GIL), threading is best suited for I/O‑bound work; for CPU‑heavy tasks you’ll want multiprocessing.