Understanding Concurrency and Parallelism: What's the Difference?

Rayen Mabrouk - Jun 18 - - Dev Community

In this article, we will discuss the concepts of concurrency and parallelism, the differences between them, and the challenges we might face while implementing them. Let's dive in 🚶‍♀️.

What is Concurrency?

To understand concurrency, let's start with a simple example.

Imagine we have an app that receives user requests, and we are operating on a single thread. This means we handle one request at a time, respond to it, and then move on to the next one.

‼️ But what happens when the number of users increases over time?

In this case, the system will become very slow, similar to a restaurant where many customers arrive, but only one person is working to serve all of them.

So, you might think of hiring more people in the restaurant to serve the customers faster.
Similarly, to handle multiple requests in the app simultaneously, we need to use multiple threads to speed up the process and improve performance.

✅ This is exactly what Concurrency means – working on multiple tasks at the same time 🤝.

What is the Difference Between Concurrency and Parallelism?

Both concurrency and parallelism aim to improve performance, but they work differently.
If you have a set of threads, each performing a specific task:

  • In Concurrency:
    The system runs them together through context switching, meaning it runs one thread for a while, then pauses it, and runs another thread, and so on until all tasks are completed.

  • In Parallelism:
    The threads run simultaneously without switching between them; they operate in parallel.

To achieve parallelism, you need a multi-core processor to run the threads in parallel. In contrast, concurrency can be achieved on a single core by context switching between threads.

Should You Always Use Multiple Threads to Improve Performance?

◀️ There are many challenges and potential issues to be aware of and avoid (which we will discuss later).
If your task is simple and doesn't require multiple threads, then avoid adding unnecessary complexity. However, if you really need to improve performance, then using multiple threads is fine.

Here are some common problems you might encounter and should be careful about to prevent issues in your application:

  • Race Condition
  • Deadlock
  • Starvation

We will discuss these problems in detail in future articles..

. . . .