Friday, May 21, 2021

Multi thread and Concurrency - Basic Understanding

 Multi thread - Why we need

  1.  Responsiveness
  2.  Performance

Multi thread, Synchronous and Asynchronous, one of the words you will here a lot.

let's take a simple example

In a supermarket people come and buy product and go to queue and purchase. In a simple scenario, there is one person who buys a large number of items and one with few items. If the customer with large items comes, other has to wait for a huge time. 

So can we reduce this ? IF yes --> How ?

In an application we have basically two parts. UI and backend

Looking at that point Responsiveness is more important to UI and Performance in backend. This is where threads become handy


Concurrency -  Multi tasking

  • Achieved by multitasking between threads
  • Concurrency == Multi tasking

Note: Even with one core we can achieve multitasking

One core -> multiple tasks concurrently

more cores -> multiple tasks parallelly


Performance Impact

  • Completing a complex task much faster
  • Finish more work in the same period of time
  • For high scale services
    • Fewer machines
    • Less money spent on hardware
    • More money save | money in pocket


Thread is a part of process and Process may have few components like

  • Process Specific
    • PID - process Id
    • Mode
    • Priority  etc
  • Files
  • Data (Heap)
  • Code
  • Thread (  there can be one or more threads)

each Thread will have

  • Stack
  • Instruction Pointer

Note: Thread will have its unique stack and Instruction pointer , but rest of the items are shared with in process context


Stack -> Region in memory, where local variables are stored, and passed in to functions

Instruction pointer -> Address of the next instruction to execute


Why we have its own stack and Instruction pointer ?

at given time each thread is executing different instructions in a different function 


Summary up to now

Why multi thread ?

Responsiveness achieved by concurrency

Performance achieved by parallelism

Thread

Stack

Instruction pointer

What thread share

files

heap(data)

code

No comments:

Post a Comment