Bitpath

Lesson 2 · Unit 01

The event loop

One thread, a queue of callbacks, no interruptions

12 exercisesabout 3 min

What you practise

  • One thread and a queue of callbacks, run-to-completion, timers and why setTimeout(0) (or call_soon) runs later, blocking the loop freezes everything

Try a question from this lesson

Pick one

The middle of this program does not print B itself: it puts that job in a queue for later. In what order do the letters appear?

queue = []

def later(job):
    queue.append(job)

print("A")
later(lambda: print("B"))
print("C")

while queue:          # the event loop
    job = queue.pop(0)
    job()
console.log("A");
setTimeout(() => console.log("B"), 0);
console.log("C");
console.log("A");
setTimeout(() => console.log("B"), 0);
console.log("C");

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

One thread, one queue

An event loop is one thread running this forever: take the next callback from the queue, run it to the end, repeat.

Timers and finished I/O do not interrupt anything. They add a callback to the queue, and it waits its turn.

So code you queue runs later, after the code that queued it.

import asyncio

async def main():
    loop = asyncio.get_running_loop()
    loop.call_soon(print, "later")
    print("running")
    await asyncio.sleep(0)  # let it run

asyncio.run(main())   # starts the loop
setTimeout(() => console.log("later"), 0);
console.log("running");
setTimeout(() => console.log("later"), 0);
console.log("running");

Python noteasyncio.run(main()) starts the loop with main as its first job. call_soon(f, x) queues the call f(x). await asyncio.sleep(0) pauses main so the loop can work through its queue.

Concept

Never block the loop

While one callback runs, nothing else can: no timers, no clicks, no other requests. There is only one thread.

A callback that computes for 2 seconds, or puts the whole thread to sleep, freezes everything for 2 seconds.

Keep callbacks short. Hand long waits to the loop instead of sitting in them.

9 more exercises in the app

  • 3× type the answer
  • 1× true or false
  • 3× multiple choice
  • 1× fill the blanks
  • 1× match the pairs

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy