Python 3D Academyবাংলা

Concurrency in Python

Chapter 32: Concurrency

8 short lessons, with 3D animations, quizzes and coding tasks.

The lessons

  1. Waiting without wasting time: async and await

    An async def function can pause at every await, and while it is paused, the event loop runs other paused functions that are ready to go on, so one worker gets through many waits at once.

  2. Doing waits together: gather and tasks

    asyncio.gather(a(), b()) (or tasks made with asyncio.create_task) runs several coroutines at once, so their waits overlap and the total time is about the longest wait, not the sum.

  3. Time limits and task groups

    asyncio.wait_for(coro, seconds) gives up with a TimeoutError if a coroutine takes too long, and a TaskGroup runs several tasks that all finish (or all get cancelled) together.

  4. Threads, processes, and how an event loop works

    Asyncio is one worker taking turns at waits, threads are several workers sharing the same memory, and processes are separate workers with their own memory; pick by whether the job mostly waits or mostly calculates.

  5. Don't block the loop: blocking calls, to_thread and cancelling

    Anything that waits without await (like time.sleep, a slow loop, or a library that isn't async) blocks the event loop: no other coroutine can run until it ends, so gather and tasks stop helping.

  6. Limits and streams: Semaphore, async for, and gather's errors

    An asyncio.Semaphore(n) holds n permits; async with sem: takes one before the block and gives it back after, so at most n coroutines are inside at once and the rest wait their turn, in order.

  7. Queues between tasks: producers and consumers

    An asyncio.Queue lets producer tasks hand items to consumer tasks: put adds an item, await get() takes the oldest one and waits while the queue is empty, and task_done() with await join() tells you when every item has been handled.

  8. Project: a log analyser

    A shop's website writes a line to a log file every time something happens: a customer logs in, a page is slow, the disk is full. On a busy day there are thousands of lines, and some are broken. When the site misbehaves, the owner wants quick answers: how many errors were there, and which error happened most? In this project you'll build that log analyser with tools from World 5: a generator, a regular expression, Counter, and a decorator that times the work. The plan in one sentence: a generator reads the log line by line and yields only the lines that fit a pattern, Counter adds them up, and a decorator records how long each report takes. Its words: log entry: one line, like 2026-10-17 09:15:07 ERROR disk full: date, time, level, message level: how serious it is: INFO, WARNING or ERROR parse: turn a line of text into its parts, here with a regex and its groups Step by step, the plan: 1. Read: readentries(lines) is a generator; for each line that fully matches the pattern, it yields (level, message) and quietly skips broken lines. 2. **Count**: countlevels builds a Counter of levels; toperrors counts the ERROR messages and asks for mostcommon(n). 3. Time: @timed wraps both counting functions and records (name, seconds) for every call. Here's the pattern picking a log line apart into its four groups: Step 1: read lazily. A log can be bigger than memory, so readentries is a generator (Lesson 26.2): it takes any iterable of lines, even an open file, and yields one entry at a time. fullmatch (Lesson 31.2) makes sure the **whole** line fits, so a broken line is skipped instead of half-matched. **Step 2: count.** A Counter (Lesson 30.1) of levels answers "how many errors?" in one line, and mostcommon(n) answers "which error happened most?". Step 3: time it. @timed (Chapter 27) wraps a function with args, *kwargs, so it fits both counting functions, measures with time.perfcounter(), and appends (func.name, seconds) to a list. **Why build it this way, and what it costs.** Each piece does one job and can be tested with a short list instead of a real log. The whole analysis is one pass to read plus one pass per report, so a log of a million lines takes about a few million steps, and because reading is lazy, memory stays small if you count straight from the generator. The decorator adds two clock readings per call, which is nothing next to the counting. **Mistakes and edge cases.** **search instead of fullmatch.** A line with extra junk at the start would still be half-matched and counted. **Using the generator twice.** countlevels(entries) uses it up, so top_errors(entries, 1) on the same generator finds nothing; make a list first, as the example does, or read the file again. A wrapper that forgets to return. Then every timed function gives back None. Timing in tests. Seconds change from run to run, so check that a timing was recorded, not its exact value.