asyncio and the Event Loop

A Python service that talks to many sockets at once, such as a gateway to several brokers or a monitor polling a set of venues, is often written with asyncio. The interview questions about it are consistent: how it differs from threads, what happens when a coroutine calls a blocking function, and where races can still happen when only one thread runs.

One thread, many waits

The event loop runs on a single thread. A coroutine runs until it reaches an await on something that is not ready, such as a socket read. It then hands control back to the loop, and the loop resumes another coroutine whose wait has finished. This is concurrency without parallelism: many operations are in progress, but only one line of Python runs at any moment.

The rest of this lesson is for subscribers

Unlock every lesson in Programming for Quantitative Developers, and every other premium course.

Subscribe to continue

Test your knowledge

Questions are only available to subscribers.

Keep reading Programming for Quantitative Developers

33 lessons in this course, and every other premium course, on one subscription.

  • Every lesson in every course, with the worked examples and interactive simulators
  • Graded questions on every lesson, with explanations for the wrong answers as well as the right one
  • The trainers, timed assessments and brainteaser library that go with them