Experiments in concurrency 3: Event loops

Click for: original source

An event loop is a loop that runs your code and does things based on some events. That’s vague, I know, but it’ll become clearer as we go. By Shalvah.

Event loop is called a loop because it really is a loop. In fact, this is basically what happens in an event loop: First, it executes your code, statement-by-statement. Then, if there are any tasks in the task queue (which your code might have added), it executes them one-by-one.

function runEventLoop() {
  runUserCode();
  while (taskQueue.isNotEmpty()) {
    runNextTask();
  }
}

The article then captures:

  • What’s an event loop?
  • Task queues
  • Timers
  • Coroutines
  • Continuations
  • Handling requests
  • Why use an event loop?

Many popular async libraries implement an event loop, including ReactPHP, async (Ruby), and EventMachine (Ruby). But it’s not just the idea of doing multiple things at once that makes event loops cool. It’s the ability to utilise “idle time”. Good read!

[Read More]

Tags app-development javascript php