What is the Multithreading. Pros and Cons.

Khayal Teyyubov
2 min readMar 31, 2022

What is Multithreading?

Multithreading is program executing technique allows you to use multiple code segments at the same process. it also sounds concurrency.

Race Conditions.

Threads using shared variables unlike process. So it leads the big problems.

Imagine you have 2 threads and you have one variable. What happen if your all threads access the same code and change variable same time. it sounds Race condition on development.

private static void RaceConditionExample()
{
Thread firstThread = new Thread(() =>
{
Add();
});
Thread secondThread = new Thread(() =>
{
Add();
});
firstThread.Start();
secondThread.Start();
foreach (var num in nums)
{
Console.Write(num); // 1 2 3 4 5 5 5
}
}
private void Add()
{
//Collection elements inline initialization
List<int> nums = new List<int> { 1, 2, 3, 4, 5 }; nums.Add(nums.Count);}

Add Method actually is the critical section. All threads want to reach Add method so this is the race condition actually. They race each other to reach Add method.

Pros And Cons of Multithreading.

Multithreading applications present the following advantages:

  • Improved performance and concurrency — For certain applications, performance and concurrency can be improved by using multithreading. In other applications, performance can be unaffected or even degraded by using multithreading. How performance is affected depends on your application.
  • ResponsivenessMultithreading in an interactive application may allow a program to continue running even if a part of it is blocked or is performing a lengthy operation, thereby increasing responsiveness to the user.
  • Resource Sharing— Processes may share resources only through techniques such as:
  • Message Passing
  • Shared Memory

Such techniques must be explicitly organized by programmer. However, threads share the memory and the resources of the process to which they belong by default.
The benefit of sharing code and data is that it allows an application to have several threads of activity within same address space.

Multithreading applications present the following disadvantages:

  • Complex debugging and testing processes
  • Overhead switching of context
  • Increased difficulty level in writing a program
  • Unpredictable results — Multithreaded programs can sometimes lead to unpredictable results as they are essentially multiple parts of a program that are running at the same time.
  • Complications for Porting Existing Code − A lot of testing is required for porting existing code in multithreading.

--

--