all Python 3threadingterm
threading
module
Threads of execution inside one process and synchronisation primitives: Lock, Event, Semaphore, Condition.
Syntax
import threading
Threads help when a program waits on I/O — network, disk; for CPU-bound work on a regular CPython build they bring no speed-up because of the GIL, and multiprocessing is the tool there. For a pool of tasks concurrent.futures.ThreadPoolExecutor is handier. The main mistake is changing shared data without a Lock: the race shows up rarely and cannot be reproduced.
Examples
import threading
results = []
def work(n): results.append(n * n)
threads = [threading.Thread(target=work, args=(i,)) for i in range(4)]
for t in threads: t.start()
for t in threads: t.join()
print(sorted(results)) # → [0, 1, 4, 9]
See also
Open in the full glossarydocs.python.orgReport an inaccuracy