In this post, I'll try to illustrate the differences between concurrency and parallelism. These terms are usually misused (I did too several times), so let's see if we can finally clear any doubts about this topic.
What is a CPU and how does it work?
A CPU is like the brain of a computer. It's where the majority of the operations are done. Also is responsible for executing the tasks we need.
A CPU can have a single core or multiple cores. Let's imagine that a CPU is a factory, and each core is a worker. The more cores a CPU has, the more work it can perform at the same time.
This is the key part. Each core can perform only one task at a time. If this point is clear, you already understood half of the topic.
So... what is parallelism?
As the word says, it's when multiple tasks are run in parallel. That means that several tasks are run at the same time. If you understood the previous point... how many cores are needed (at minimum) if you want to run two tasks in parallel?
Since one core can perform only one task at a time, you'll need at least 2 cores. If you have more than two, the rest of the cores are going to be idle, because 1 task -> 1 core.
Ok, but what is concurrency?
Nice! We understood parallelism, let's dive into concurrency now!
You can think about concurrency as an illusion of parallelism. Let me explain that.
Imagine someone working in customer service. That person has to serve two queues of people, but there is only one employee. So the person decides to go with the first customer in the first queue. If that customer has to fill out a form or perform any other task that doesn't need the attention of the employee, the person goes to the second queue. If the same situation happens or the client in the first queue finishes the task, the employee comes back. Repeating that process creates an illusion of parallelism. As seen from the outside, it may look like the employee is serving both queues at the same time.
The same thing happens in a CPU. Since we are working with a single core, just one task at a time can be performed. But the CPU, by fast switching between the two tasks, creates an illusion of parallelism.
Conclusion
You have learned the differences between parallelism and concurrency. You learned that one core can work on just one task at the same time. If you want to run two tasks in parallel, you need a CPU with (at least) two cores. If your CPU is a single core and want to run two tasks at (almost) the same time, you need to use concurrency. In concurrency, the CPU switches very fast between the two tasks, creating an illusion of parallelism.
Top comments (0)