🎓 A1Learner
🔍

Python Threads

A thread is one path of execution inside a program. Two threads can run side by side.

Make and start a thread

A worker function holds the work. The thread runs that function.

import threading

def greet():
    print("Hello from a thread")

t = threading.Thread(target=greet)
t.start()
t.join()

start() is not run()

Calling run() stays on the main thread. Calling start() moves to the new thread.

import threading

def show_name():
    print(threading.current_thread().name)

wrong = threading.Thread(target=show_name, name="worker")
wrong.run()
right = threading.Thread(target=show_name, name="worker")
right.start()
right.join()

Wait with join()

join() pauses your code at that line. The next line runs after the worker ends.

import threading

results = []

def work():
    results.append("done")

t = threading.Thread(target=work)
t.start()
t.join()
print(results)
print(t.is_alive())

A daemon thread

Set daemon=True for background work. The program can end without waiting for it.

import threading

def tidy():
    print("tidying")

t = threading.Thread(target=tidy, daemon=True)
print(t.daemon)

Pass arguments

args carries values into the worker. The worker uses them like normal parameters.

import threading

results = []

def add(a, b):
    results.append(a + b)

t = threading.Thread(target=add, args=(3, 4))
t.start()
t.join()
print(results)

Example

import threading

results = [0, 0, 0]

def total(start, end, index):
    results[index] = sum(range(start, end + 1))

threads = []
ranges = [(1, 10), (11, 20), (21, 30)]
for i, (start, end) in enumerate(ranges):
    t = threading.Thread(target=total, args=(start, end, i))
    threads.append(t)
    t.start()

for t in threads:
    t.join()

for i, value in enumerate(results):
    print(f"Thread {i + 1}: {value}")
print(f"Total: {sum(results)}")

Key points

  • Thread: one path of execution inside a program
  • Use threading.Thread to make a thread for a worker function
  • Use start() to run the worker in a new thread
  • Use join() to wait until a thread has finished
  • Daemon thread: a background thread that does not keep the program alive
  • Use args to pass values into the worker function
  • Threads in one program share the same variables.
  • Threads suit work that can wait or proceed in parallel.

In this example, results starts as three zeroes, one slot per thread. The total function adds a range of numbers into its own slot. The loop makes three threads, one for each range. Each thread gets its range and its slot number through args. The main code then joins every thread and waits for all sums. The prints run only after the joins, so the order is fixed. Thread 1 sums 1 to 10 and gets 55. Thread 3 sums 21 to 30 and gets 255. The last line adds the three slots and prints 465.

Note

Calling run() by mistake runs the work on the current thread, not a new one

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

You call t.run() instead of t.start(). What happens?