18/28
Part 5 of 6 · Errors and shared stateLearn and do

Who owns the visited set

Shared state is where threaded code breaks. In this design, who touches what?

With one coordinator, nothing is shared

ThreadTouches
the coordinatorseen and pending: the only thread that reads or writes them
each workerfetch(url) only: it takes a URL and hands back the links through the future

Shared state needs an owner. In the coordinator design, the owner is the main thread: only it reads or writes seen and pending. Workers run fetch(url) and hand back a list through the future. Nothing they touch is shared, so nothing needs a lock.

With workers that decide, the check and the add are one step

import queue
import threading


def crawl(
    start_url: str, fetch: Callable[[str], list[str]], max_workers: int = 8
) -> set[str]:
    """Each worker fetches a page, then checks and queues its links."""
    start = urldefrag(start_url).url
    host = urlparse(start).hostname
    seen, lock = {start}, threading.Lock()
    # URLs to fetch, then one None per worker
    todo: queue.Queue[str | None] = queue.Queue()
    todo.put(start)

    def worker() -> None:
        """Takes URLs from todo until it gets None."""
        while (url := todo.get()) is not None:
            try:
                for link in fetch(url):
                    link = normalize(url, link)
                    if urlparse(link).hostname != host:
                        continue
                    # check and add, one step
                    with lock:
                        if link in seen:
                            continue
                        seen.add(link)
                    # the page's links go in first
                    todo.put(link)
            except Exception as exc:
                log.warning("fetch failed for %s: %r", url, exc)
            finally:
                # then the page counts as done
                todo.task_done()

    threads = [threading.Thread(target=worker) for _ in range(max_workers)]
    for t in threads:
        t.start()
    # unfinished count reached zero
    todo.join()
    for _ in threads:
        # one stop signal per worker
        todo.put(None)
    for t in threads:
        t.join()
    return seen

This is the other classic design. It hands the decisions to the workers. Each worker takes a URL from a queue.Queue, a queue that many threads can share safely, fetches it, and puts the new links back. Now every worker touches seen.

In the editor, 20 threads each try to claim /a at the same moment. Write claim(url): under lock, return False if url is in seen, else add it and return True, so exactly one thread wins.