I was learning about Concurrency and Parallelism, So both the terms have very similar definitions and that creates a very important question.
What is the difference between the term Concurrency and Parallelism?
So, I will answer this question in the blog.
Concurrency is when two or more tasks are running at an overlapping time. In a more generalized way, we can say at least two threads are making progress. Concurrency means executing more than two tasks at the same time but not simultaneously.
CPU can only execute one task at the same time, So what the CPU does is that it executes a little bit of one task at a time then switch on another task and make it a little bit in progress then again switch on other tasks, and here tasks are representing the threads. The switching process is fast so as a user it seems more than one task is making progress concurrently at the exact same time.
The Process of switching between two threads to storing or restoring CPU state is Context switching.
Concurrency in Multitasking:-
In Programming, we can write multiple programs on a single execution core where only a single task can execute at a given time. Multiple tasks can be executed in provided time by the scheduler. The Scheduler provides a fixed amount of time to each process and that gives the illusion of parallelism to the users.
In this figure, Two threads are working on generated Instructions of Application. Here, The CPU will execute instructions in a time slice manner. We don’t know how much code will be executed before the scheduler decides to take the running thread out and allow another thread for execution.
Other processes running at an equivalent time might need some CPU time. Schedulers use a priority mechanism to schedule the CPU time to run a thread.
Parallelism means dividing an Application into subtasks. And then perform execution of each and every task simultaneously on multiple threads.
In this figure, Task splits up into 4 subtasks. Each task is being executed by 4 threads, which are running on 2 CPUs. It means tasks executed on the same CPU are running concurrently. Tasks that are executed on different CPUs are running parallelly.
If the 4 subtasks were executed by 4 threads running on each of their CPU, then the task execution would have been fully parallel.
Parallel Execution :-
In Parallel Execution, two or more tasks are running simultaneously. We can say two threads are executing at the same time.
In Parallel execution, Our computer has more than one CPU core to execute more than one task at an equivalent time.
Parallel execution provides:-
- Faster execution.
- Execute tasks independently in less time.
Through this blog, You will get to know about the difference between both the terms Concurrency and Parallelism. The concept of parallelism and concurrency is a powerful feature of programming languages and it makes execution faster.