Concurrency (Synchronous) vs Parallelism (Asynchronous) vs Thread
Or MultiThread
Concurrency and Parallelism -> Way tasks are executed.
Synchronous and Asynchronous -> Programming model.
Single Threaded and Multi-Threaded -> The environment of task
execution.
Concurrency
Consider you are given a task
of singing and eating at the same time. At a given instance of time either you
would sing or you would eat as in both cases your mouth is involved. So, in
order to do this, you would eat for some time and then sing and repeat this
until your food is finished or song is over. So, you performed your tasks
concurrently.
Concurrency
means executing multiple tasks at the same time but not necessarily
simultaneously.
Parallelism
Consider you are given two tasks of cooking and speaking
to your friend over the phone. You could do these two things simultaneously.
You could cook as well as speak over the phone. Now you are doing your tasks
parallelly.
How Is Concurrency Related
To Parallelism?
Concurrency and Parallelism
refer to computer architectures which focus on how our tasks or computations
are performed.
i.
Single core environment, concurrency happens with tasks
executing over same time period via context switching i.e at a particular time
period, only a single task gets executed.
ii.
Multi-core environment, concurrency can be achieved via parallelism in
which multiple tasks are executed simultaneously.
Threads & Processes
Threads
Threads are a sequence of
execution of code which can be executed independently of one another. It
is the smallest unit of tasks that can be executed by an OS. A program can be
single threaded or multi-threaded.
Process
A process is an instance of
a running program. A program can have multiple processes. A process
usually starts with a single thread i.e a primary thread but later down the
line of execution it can create multiple threads.
Synchronous & Asynchronous
Synchronous
Imagine you were given to write two letters one to
your mom and another to your best friend. You cannot at the same time write two
letters unless you are a pro ambidextrous.
In a synchronous programming model, tasks are executed one after another.
Each task waits for any previous task to complete and then gets executed.
Asynchronous
Imagine you were given to make a sandwich and wash
your clothes in a washing machine. You could put your clothes in the washing
machine and without waiting for it to be done, you could go and make the
sandwich. Here you performed
these two tasks asynchronously.
In an asynchronous
programming model, when one task gets executed, you could switch to a different
task without waiting for the previous to get completed.
What is the role of
synchronous and asynchronous programming in concurrency and parallelism?
i.
Synchronous programming model helps us to achieve concurrency.
ii.
Asynchronous programming model in a
multi-threaded environment is a way to achieve parallelism.
No comments:
Post a Comment