Beyond the Event Loop
Did you know that the event loop is one of many different concurrency models?
At this point, you might be wondering why you should read this article. The answer is simple, to gain technical breadth to become a software architect!
If you come from Javascript you should be familiar with the Event Loop to prevent the website from being frozen by different tasks like fetching something from the backend.
…But did you know it’s just one of many concurrency models?
Yes, and there are more concurrency models that we will explain later, but let’s start with the basics.
What’s concurrency?
Concurrency is when two or more tasks are executed simultaneously. But simultaneously is not necessary at the same time.
The simplest example is a single cashier that attends to people from 2 or more lines.
Event-driven
Let’s start with the Event loop since it’s what we are familiar with. If you don’t know anything about the event loop I strongly recommend you watch this video.
Threads & locks
The idea here is simple, we span several threads to execute multiple tasks, but this approach is known for several problems like deadlock where thread A cannot complete because it’s waiting for thread B to finish, but thread B is waiting for A to finish.
Functional Programming
FP has several principles like immutable state & side effects should be minimal which helps against the problems that threads & locks have.
Also, FP could be used in multithreaded environments without carrying much about any locking strategy.
Actors
The actor model focuses on how the components of a system interact with each other and how it should behave.
Actor
Is a fundamental unit of computation, it can perform actions like:
Create an actor
Send a message
Define how to handle the next message
The actors are isolated from each other, in other words, don’t share memory. And each actor has its own “mailbox”.
The mailbox is used to receive messages and each message is processed sequentially.
Erlang uses the actor model.
Communicating Sequential Processes (CSP)
Channels are used for communication and synchronization. Processes are coupled to the channel.
A channel writes is blocked until a reader channel reads it. This is an advantage because the channel would hold only one message
Go (programming language) implements CSP
At this point, if you were to leave this post, just keep the following three points:
The event loop is just an implementation of the event-driven concurrency model
Things to consider when working with different concurrency models:
Sharing state
Consistency/inconsistency.
Locking strategies
Deadlocks
Race conditions