Threads and the GIL
Understand Python threading limits.
What Is a Thread?
A thread is a separate flow of execution inside one process. Python's threading module lets you run functions concurrently within a single program.
import threading
def worker():
print('hello from thread')
t = threading.Thread(target=worker)
t.start()
t.join()
print('main done')Starting Multiple Threads
You can launch several threads. Each runs its target function. join() makes the main thread wait until a thread finishes.
import threading
def task(name):
print('task', name)
threads = [threading.Thread(target=task, args=(i,)) for i in range(3)]
for t in threads:
t.start()
for t in threads:
t.join()
print('all finished')All lessons in this course
- Threads and the GIL
- ThreadPoolExecutor
- multiprocessing Basics
- Sharing Data Safely