DEV Community

YEJIN LEE
YEJIN LEE

Posted on

Multi Threading

What is the Multi Thread?
A thread is the smallest unit of execution, and multithreading improves performance by enabling taskes to run simultaneously.

Image description
(sharing code, data, files)

It refers to the ability of a processor to execute multiple threads concurrently within a single process!

On a single-core CPU, threads are executed one at a time, switching so quickly that it apprears they run simultaneously.

For example, Google Chrome uses multithreading when handling multiple tabs and rendering web pages. Each tab is a separate process.

Page Rendering

  • You're scrolling a web page(Main Thread)
  • At the same time, a background thread is processing a large Json file fetched from an API.(Worker Thread)
  • The web page remains smooth and responsive because the heavy computation is offloaded to a worker thread.

Tabs and Isolation

  • You open two tabs, one playing a YouTube and the other loading a news website.
  • The video tab uses thread for video decoding, audio playback, and rendering, while the news tabs uses threads to load and display content!
  • Even if the news tab's scripts are slow, the video playback in the other tab remains unaffected.

but, It can also make problem..
DisAdvantages of Multithreading

1 - Race condition occurs when two or more threads attempt to modify shared data at the same time, leading to unpredictable results.

let's imagine two threads accessing a bank account balance.
if both thread read the balance at the same time, modify it without proper synchronization, the final balance could be incorrect ㅜ.ㅜ

2 - Deadlock happens when two or more threads are waiting for each other to release resources, resulting in a standstill.
This causes the threads to be stuck indefinitely, as no one can continue.

Thread A locks resource 1 and waits for resource 2,
while Thread B locks resource 2 and waits for resource 1.
Both threads are now blocked, causing a deadlock.

3 - Context Switching is the process where the CPU switches from executing one thread to another. When threre are many threads, the CPU spends a significant amount of time saving and loading states, which leads to performance degradation!

How can I use MultiThreading in server engineering?

  • A server needs to handle many incoming requests from multiple clients. the server can handle multiple client requests at the same time. Each request is assigned to a separate thread or thread pool, allowing them to be processed concurrently. without it, each request would have to be processed sequentially, which could significantly slow down response.

Top comments (0)