Threads and concurrent.futures

A thread runs a function alongside the rest of your program. For I/O-bound work, the easiest way to use threads is a pool from concurrent.futures:

from concurrent.futures import ThreadPoolExecutor
import urllib.request

def fetch(url: str) -> int:
    with urllib.request.urlopen(url) as resp:
        return len(resp.read())

urls = ["https://python.org", "https://pypi.org", "https://docs.python.org"]
with ThreadPoolExecutor(max_workers=3) as pool:
    sizes = list(pool.map(fetch, urls))   # results in the same order as urls

Three downloads that take a second each finish in about one second, not three. pool.submit(fn, arg) returns a future: a handle you can ask for the result later.

The browser can't start threads, so this code doesn't run here. The program does the same work with a plain loop and times it, so you can see what the pool would save.

Run it. Each "fetch" waits 0.05 s. With a pool of 3, the total would be about 0.05 s.