Python Concurrency · Lesson 139 of 149

Python Threads

What you will learn

  • What a thread is and how to start and join one
  • Why threads help with waiting (I/O) but not with computing
  • Race conditions and locks
  • Passing work with queue.Queue, signalling with Event
  • Daemon threads and exceptions in threads
  • A worker pool example

1. What is a thread?

A thread is a separate flow of control inside one program. Every program starts with one, the main thread. With the threading module you start more. All threads of a program share the same memory (the same variables and objects), which makes passing data easy and also makes mistakes easy (section 4).

import threading
import time

Threads suit I/O-bound work (lesson 20.1): while one thread waits for the network, disk or a timer, others run. Python's threads do not run Python code in parallel on several cores (lesson 20.6 explains why), so they do not speed up heavy calculations.

2. Starting and joining threads

def worker(name, seconds, results):
    time.sleep(seconds)
    results.append(name)


results = []
threads = [threading.Thread(target=worker, args=(f"t{i}", 0.5, results)) for i in range(4)]

start = time.perf_counter()
for t in threads:
    t.start()
for t in threads:
    t.join()
print(f"4 waits of 0.5 s in threads: {time.perf_counter() - start:.2f} s", sorted(results))
4 waits of 0.5 s in threads: 0.50 s ['t0', 't1', 't2', 't3']

Four waits of half a second, one after another, take 2 seconds (lesson 20.1); in four threads they took 0.5 seconds, because all four waited at once.

  • Thread(target=function, args=(...)) creates a thread (it does not run yet).
  • t.start() begins running function in the new thread.
  • t.join() makes the caller wait until that thread finishes. Always join threads whose results you need.
  • Do not call the function yourself (target=worker(...) runs it at once in the main thread); pass the function and its arguments separately.

Useful facts:

t = threading.Thread(target=lambda: None, name="helper")
print(t.name, t.is_alive(), threading.current_thread().name, threading.active_count())
t.start()
t.join()
print(t.is_alive())
helper False MainThread 1
False

A thread can be started only once. is_alive() tells whether it is still running.

Quick check: what does `t.join()` do?

It blocks the calling thread until thread t has finished.

3. Threads do not speed up computing

Four CPU-bound tasks, sequentially and in four threads (from the check computer):

cpu tasks sequential 0.42 s, threaded 0.47 s

The threaded version was not faster, in fact slightly slower: only one thread can execute Python code at any moment (lesson 20.6). For calculations use processes (lesson 20.3). For waiting, threads work well.

4. Race conditions and locks

Because threads share memory, two threads changing the same data can interfere. A race condition is a bug whose result depends on the exact timing of the threads.

Here four threads each add 1 to a shared counter 2,000 times. Each step reads the counter, then writes back value + 1. If another thread runs between the read and the write, its update is lost. The time.sleep(0) marks a point where Python may switch threads, to make the problem visible every time:

counter = {"n": 0}


def unsafe(times):
    for _ in range(times):
        value = counter["n"]
        time.sleep(0)               # lets another thread run between read and write
        counter["n"] = value + 1
expected 8000
without lock: 2000 2295

Two runs gave 2,000 and 2,295 instead of 8,000: most updates were lost, and the answer even changed between runs. A lock allows only one thread at a time into a protected section:

lock = threading.Lock()


def safe(times):
    for _ in range(times):
        with lock:
            value = counter["n"]
            time.sleep(0)
            counter["n"] = value + 1
with lock:    8000 8000

With the lock, both runs gave exactly 8,000. Points to remember:

  • Use with lock: (not separate acquire() and release() calls), so that the lock is released even after an error (lesson 14.6).
  • Keep the locked section short.
  • A simple counter += 1 without any pause happened to give the right answer in the check (400000 for 4 threads times 100,000), but that is luck, not a guarantee: do not rely on it.
  • Two locks taken in different orders by different threads can cause a deadlock, where each waits for the other forever. Prefer one lock, or a fixed order.
  • Other tools: RLock (a lock the same thread can take again), Semaphore (allow N threads in), Condition, Barrier.

The best protection is not sharing: let each thread work on its own data and combine the results afterwards, or pass data through a queue (next section).

5. Queue and Event

queue.Queue is a thread-safe waiting line. It does its own locking, so threads can put and take items without extra care. It is the standard way to hand out work and collect results:

import queue

q = queue.Queue()
out = []


def consumer():
    while True:
        item = q.get()
        if item is None:           # a signal meaning "no more work"
            break
        out.append(item * item)
        q.task_done()


c = threading.Thread(target=consumer)
c.start()
for i in range(5):
    q.put(i)
q.put(None)
c.join()
print("squares:", out)
squares: [0, 1, 4, 9, 16]

put adds an item, get waits for and removes one, task_done plus q.join() lets a producer wait until all items have been handled, and the special value None is a common way to tell workers to stop.

threading.Event is a flag threads can wait on:

ev = threading.Event()
seen = []


def waiter():
    ev.wait()
    seen.append("go")


w = threading.Thread(target=waiter)
w.start()
time.sleep(0.1)
print("before set:", seen)
ev.set()
w.join()
print("after set:", seen)
before set: []
after set: ['go']

wait() blocks until another thread calls set(). Events are useful to signal "start now" or "please stop". Another useful object is threading.local(), whose attributes are separate for each thread.

6. Daemon threads and errors

A daemon thread (daemon=True) does not keep the program alive: when the main thread ends, daemon threads are stopped abruptly. Use it for background jobs that need no clean-up:

d = threading.Thread(target=lambda: time.sleep(30), daemon=True)
d.start()
print("daemon:", d.daemon, d.is_alive())
daemon: True True

A normal thread keeps the program running until it finishes. There is no safe way to kill a thread from outside; design threads to check an Event and stop themselves.

An exception inside a thread ends only that thread; the main thread does not see it (it is printed to the error stream by default). A thread's function should catch the errors it expects, and you can install your own threading.excepthook:

def boom():
    raise ValueError("inside thread")


errors = []
threading.excepthook = lambda args: errors.append(repr(args.exc_value))
b = threading.Thread(target=boom)
b.start()
b.join()
print("caught by hook:", errors, "| main still running")
caught by hook: ["ValueError('inside thread')"] | main still running

(Lesson 20.4 shows a better way to get results and errors back from workers.)

7. When to use threads

Good fit Poor fit
downloading many pages or files heavy calculations (use processes)
waiting for several slow services very many thousands of tasks (use asyncio, lesson 20.5)
keeping a program responsive while a slow job runs code full of shared, changing data
simple background tasks such as saving or logging when a simple loop is fast enough

For most programs, concurrent.futures.ThreadPoolExecutor (lesson 20.4) is simpler than managing Thread objects by hand.

Worked example: a pool of three workers

Six "pages" take between 0.2 and 0.6 seconds to download (simulated with sleep). We fetch them one after another, then with three worker threads that take jobs from a queue and store the results under a lock.

import queue
import threading
import time

PAGES = {"home": 0.4, "news": 0.6, "shop": 0.5, "blog": 0.3, "faq": 0.2, "help": 0.5}


def fetch(name, delay):
    """Pretend to download a page: wait, then return its size."""
    time.sleep(delay)
    return len(name) * 100


def sequential():
    return {name: fetch(name, delay) for name, delay in PAGES.items()}


def with_worker_pool(workers=3):
    jobs = queue.Queue()
    results = {}
    lock = threading.Lock()

    def worker():
        while True:
            job = jobs.get()
            if job is None:
                break
            name, delay = job
            size = fetch(name, delay)
            with lock:
                results[name] = size
            jobs.task_done()

    threads = [threading.Thread(target=worker) for _ in range(workers)]
    for t in threads:
        t.start()
    for item in PAGES.items():
        jobs.put(item)
    jobs.join()
    for _ in threads:
        jobs.put(None)
    for t in threads:
        t.join()
    return results


for label, func in [("one after another", sequential),
                    ("3 worker threads", with_worker_pool)]:
    start = time.perf_counter()
    results = func()
    elapsed = time.perf_counter() - start
    print(f"{label:<20} {elapsed:4.2f} s  {len(results)} pages  total size {sum(results.values())}")
print(sum(PAGES.values()), "seconds of waiting in total")
one after another    2.50 s  6 pages  total size 2300
3 worker threads     1.10 s  6 pages  total size 2300
2.5 seconds of waiting in total
Observation Why
2.50 s sequentially the six waits add up to 2.5 s
1.10 s with three workers three waits overlap; the best possible is about 0.83 s (2.5 / 3), and the uneven job lengths and the order of the queue cost a little more
same pages and total size the results are the same as before: concurrency changed the timing, not the answer
queue.Queue hands out jobs safely; None stops each worker
with lock: around results[name] = size one thread at a time updates the shared dictionary

The pages are simulated: nothing was downloaded. The timings are from one computer and will vary.

Common mistakes

  • Using threads for CPU-heavy work and expecting a speed-up.
  • Sharing data without a lock (race conditions that appear only sometimes).
  • Calling the function instead of passing it: Thread(target=f(1)).
  • Forgetting join(), so the program ends or reads results too early.
  • Too many threads, or too many requests at once to one server.
  • Holding a lock while doing slow work, or taking two locks in different orders (deadlock).
  • Relying on the order in which threads finish.
  • Trying to kill a thread instead of asking it to stop.

Key takeaways

  • A thread is a flow of control inside a program that shares its memory; create with Thread(target=f, args=(...)), then start() and join().
  • Threads overlap waiting (I/O-bound work), but do not speed up Python calculations.
  • Shared changing data needs a Lock (with lock:), or better, no sharing: use queue.Queue to pass work and results.
  • Event signals between threads; daemon threads end with the program; exceptions in a thread stay in the thread.
  • Prefer ThreadPoolExecutor (lesson 20.4) for everyday tasks.

Practice

1. What is the difference between start() and calling the target function directly?

Show answer

start() runs the function in a new thread; calling it directly runs it in the current thread, so there is no concurrency.

2. Why did the unlocked counter end with far less than 8,000?

Show answer

Threads read the same old value, and each wrote back value + 1, overwriting one another's updates (a race condition).

3. What does with lock: guarantee?

Show answer

That only one thread at a time runs the indented block, and that the lock is released afterwards even if an error occurs.

4. How can workers be told to stop when using a Queue?

Show answer

Put a special value such as None on the queue for each worker; a worker that receives it breaks out of its loop.

5. Why are threads a poor choice for computing prime numbers?

Show answer

Only one thread can run Python code at a time, so the calculation is not sped up; processes are the right tool.

6. What happens to a daemon thread when the main program ends?

Show answer

It is stopped abruptly, with no chance to clean up.