Reading history

Python Threading and concurrent.futures

6 min read 0 views

Run waiting tasks in parallel with ThreadPoolExecutor, start and join threads, protect shared data with Lock, use as_completed and understand the GIL.

Many programs spend most of their time waiting: for a web page to download, a file to be read or a database to reply. Threads let a program wait for several of these things at once, so four one-second downloads take about one second instead of four. This lesson shows the simple way, ThreadPoolExecutor, then threads by hand, locks for shared data, and how to collect results and errors.

In this lesson you will learn

  • Running tasks in parallel with ThreadPoolExecutor
  • Starting and joining threads with threading.Thread
  • Protecting shared data with a Lock
  • Getting results as they finish with as_completed
  • When threads help and when they do not (the GIL)

You should know functions, lambda functions and context managers.

Waiting in Parallel

import threading
import time
from concurrent.futures import ThreadPoolExecutor

def download(name, seconds):
    time.sleep(seconds)               # stands in for waiting on the network
    return f"{name} ({seconds}s)"

files = [("photo.jpg", 0.3), ("report.pdf", 0.3), ("song.mp3", 0.3), ("video.mp4", 0.3)]

start = time.perf_counter()
for name, sec in files:
    download(name, sec)
one_by_one = time.perf_counter() - start

start = time.perf_counter()
with ThreadPoolExecutor(max_workers=4) as pool:
    results = list(pool.map(lambda f: download(*f), files))
together = time.perf_counter() - start

print("results:", results)
print(f"one by one: about {one_by_one:.1f}s")
print(f"4 threads:  about {together:.1f}s")

# Starting threads by hand
done = []
def worker(n):
    time.sleep(0.05 * n)
    done.append(n)

threads = [threading.Thread(target=worker, args=(n,)) for n in (3, 1, 2)]
for t in threads:
    t.start()
for t in threads:
    t.join()                          # wait for each to finish
print("finished in order:", done)

Output

results: ['photo.jpg (0.3s)', 'report.pdf (0.3s)', 'song.mp3 (0.3s)', 'video.mp4 (0.3s)']
one by one: about 1.2s
4 threads:  about 0.3s
finished in order: [1, 2, 3]
  • time.sleep stands in for a slow network request. Done one after another, four 0.3-second downloads take about 1.2 seconds.
  • ThreadPoolExecutor(max_workers=4) creates a pool of four worker threads. pool.map hands each file to a free worker and returns the results in the original order. All four wait at the same time, so the total is about 0.3 seconds. Your exact timings may differ slightly.
  • The with block waits for every task to finish before continuing, and then shuts the pool down.
  • You can also create threads yourself: Thread(target=worker, args=(n,)), then start() to begin and join() to wait. The workers finish in order of how long they sleep, not the order they were started.

Locks, Results and Errors

import threading
import time
from concurrent.futures import ThreadPoolExecutor, as_completed

# A Lock lets only one thread at a time run the protected block
balance = 0
lock = threading.Lock()

def deposit_many(times):
    global balance
    for _ in range(times):
        with lock:
            balance += 1              # read, add, write: must not be interrupted

threads = [threading.Thread(target=deposit_many, args=(100_000,)) for _ in range(4)]
for t in threads: t.start()
for t in threads: t.join()
print("balance with lock:", balance)

# as_completed hands back each result as soon as it is ready
def check_site(name, delay, ok=True):
    time.sleep(delay)
    if not ok:
        raise ConnectionError(f"{name} did not answer")
    return f"{name} is up"

jobs = [("bank", 0.3, True), ("school", 0.1, True), ("shop", 0.2, False)]
with ThreadPoolExecutor() as pool:
    futures = {pool.submit(check_site, *job): job[0] for job in jobs}
    for fut in as_completed(futures):
        try:
            print(" ", fut.result())
        except ConnectionError as e:
            print("  error:", e)

Output

balance with lock: 400000
  school is up
  error: shop did not answer
  bank is up
  • balance += 1 looks like one step but is really three: read the value, add one, write it back. If two threads interleave those steps, one update can be lost. This is called a race condition.
  • with lock: lets only one thread at a time into the block, so all 400,000 deposits are counted. Keep locked blocks short, because other threads wait while one holds the lock.
  • pool.submit starts one task and returns a Future, an object that will hold the result later. as_completed yields futures as soon as each one finishes: the quick school check first, the slow bank check last.
  • If a task raises an exception, it is stored in its future and raised again when you call result(), so one failing site can be reported without stopping the others.

Threads, Processes or asyncio?

In the standard version of Python (CPython), the Global Interpreter Lock (GIL) lets only one thread run Python code at any moment. Threads still help with waiting, because a thread that is sleeping or waiting for the network releases the GIL. For heavy calculation, use processes instead.

WorkBest tool
Many downloads, files or database calls (I/O-bound)ThreadPoolExecutor
Heavy number crunching (CPU-bound)ProcessPoolExecutor or multiprocessing
Thousands of network connections at onceasyncio

Common Mistakes

  1. Using threads to speed up pure calculation, which the GIL prevents. Use processes.
  2. Changing shared data without a lock, causing rare, hard-to-repeat bugs.
  3. Forgetting join(), so the main program uses results before the threads finish.
  4. Never calling result() on futures, so exceptions inside tasks are silently ignored.

Practice Exercises

Exercise 1. Use ThreadPoolExecutor to compute the length of each word in ["Dhaka", "Rajshahi", "Cox's Bazar"] and print the list.

Show answer
from concurrent.futures import ThreadPoolExecutor
words = ["Dhaka", "Rajshahi", "Cox's Bazar"]
with ThreadPoolExecutor() as pool:
    print(list(pool.map(len, words)))   # [5, 8, 11]

This works, but for tiny tasks like this threads add overhead. They pay off only when each task waits.

Exercise 2. Why is balance += 1 unsafe without a lock, but with lock: balance += 1 safe?

Show answer

Without a lock, two threads can both read the same old value, add one and write back the same new value, so one deposit is lost. The lock makes the read-add-write sequence run for one thread at a time.

Frequently Asked Questions

Is the GIL going away?

Python 3.13 introduced an optional “free-threaded” build without the GIL, and Python 3.14 made it officially supported. It is still a separate, optional build: the standard Python download keeps the GIL, so plan for it in everyday code.

How many workers should a pool have?

For waiting-heavy tasks, more workers than processor cores is fine; the default is a sensible number based on your CPU. For downloads from one website, keep it small so you do not overload the server.

Summary

  • Threads let a program wait for several slow operations at the same time.
  • ThreadPoolExecutor with map or submit is the easiest way to use them.
  • Protect shared data with a Lock.
  • Because of the GIL, use processes, not threads, for heavy calculation.

Next: Python asyncio.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *