4 Matching Annotations
  1. Nov 2025
    1. Asyncio

      Async (Cooperative Multitasking) The Model: There is one thread (one worker).

      The Control: The code decides when to switch tasks.

      Mechanism: When your code hits await (or yield), it voluntarily hands control back to the Event Loop.

      Analogy: A single chess master playing against 50 opponents simultaneously. The master makes a move on Board 1, then immediately walks to Board 2. There is only one person moving pieces, but 50 games are progressing.

      Multithreading (Preemptive Multitasking) The Model: There are multiple threads (multiple workers).

      The Control: The Operating System decides when to switch tasks.

      Mechanism: The OS slices time into tiny chunks. It runs Thread A for 10ms, then forcibly pauses it (interrupts) to run Thread B for 10ms. Thread A has no say in this.

      Analogy: 50 novice chess players playing 50 games. They play at the same time, but they crowd the room, bump into each other, and consume more resources (space/food).

    2. Await

      imagine a waiter (The Event Loop) and a table of customers (The Tasks).

      Synchronous (Blocking): The waiter takes an order from Table 1. He walks to the kitchen and stands there waiting for the chef to cook the food. He ignores Table 2, Table 3, and Table 4. Nothing else happens in the restaurant until Table 1 eats.

      Asynchronous (await): The waiter takes an order from Table 1 (await food). He gives the ticket to the kitchen. instead of waiting, he immediately turns around and goes to serve Table 2. When the kitchen rings the bell (Task done), he goes back to Table 1.

    3. When a class has the __await__ method, we can use the await keyword in front of an instance of the class to call it.

      Why is await written that way? The implementation while not self.finished: yield self is a pattern often referred to as a Trampoline.

      When you await task, Python essentially does yield from task.await().

      The yield self hands control back to the Event Loop (via the pipeline we discussed earlier).

      The Event Loop sees the task isn't done, so it puts it back in the queue.

      When the loop comes back to this task, the while loop in await runs again, yielding again.

      This continues until self.finished becomes True.