all the code in an event loop runs in a single operating system thread, so only one piece of code can be running at any given time.
for example, in node.js all the Javascript code runs in a single thread, but there are other worker threads that handle making network requests and other I/O.
for example, with Python's asyncio
, the code that does the
scheduling is a Python program
often event loops are implemented as a while loop that looks something like this:
while True: self._run_once() if self._stopping: break
(the above is the literal exact code from python's asyncio event loop)
functions get pushed onto the queue when they're ready to run, and then the event loop runs functions from the queue in order
functions can get pushed onto the event loop's queue because a network request or some other I/O finished, or the user clicked something, or because the function was scheduled to run at that time, etc
async functions are special because they can be "paused" and restarted later by the event loop. For example, in this Javascript code:
async function panda() { let x = 3; await elephant(); let y = 4; }the event loop schedules
elephant()
, pauses
panda
, and schedules panda()
to restart after
elephant()
is finished running. Normal non-async functions can't be
paused and restarted like this. Another name for these async functions that can be paused and restarted is coroutines.
setTimeout
in Javascript), is it guaranteed to
run at that exact time?
the event loop will do its best, but sometimes functions get delayed
setTimeout
and async/await and
callbacks in Javascript all use the same event loop?
the syntax is different, but they're all different ways for you to schedule code to run later
x = 3; y = 4;is it possible for the event loop to interrupt after
x=3
and run something else?
you need to yield to the event loop for it to run a different function,
for example with await
while(true) { i = i * 3 }will the event loop eventually interrupt the code?
you can usually block the event loop for as long as you want by running something CPU-intensive.
if your event loop's CPU is always busy, then new events that come in won't get handled on time because the CPU will be busy.
at least in node.js and in the browser, there's always an event loop that Javascript code runs on.
it's possible that there's some other Javascript runtime that doesn't use an event loop but I don't know about it
there are a lot of different event loop implementations in different programming languages.
most programming languages don't have the same "everything runs on the event loop" model as Javascript, but many languages have event loop libraries. And in theory you can always write your own event loop library if it doesn't exist already.
_run_once
function to be a great overview of how exactly an event loop actually works