What is multithreaded programming?

Operating SystemHardwareSoftware & Coding

A thread is a small unit of CPU utilisation. It comprises a thread ID, a program counter, a register set and a stack. It shares with other threads which belong to the same process having code segment, data section and other operating system resources like open files and signals.

A heavy weight process has a single thread of control. If a process has multiple threads of control, it can perform more than one task at a time. Many software packages that run in modern PC’s are multi-threaded. Here, the application is implemented as a separate process with several threads of control.

For example − Consider a word processor consisting of a thread for displaying graphics, another thread for responding to keystrokes from the user and a third thread for performing spelling and grammar checking.

Refer the diagram of single thread and multi-thread process −

Single Thread

Multithreaded process

Similarly a single application requires performing several same tasks.

For example − A web server accepts client requests for web pages, images etc. A web server may have several clients concurrently accessing it. Suppose, if the web server is running as a single threaded process, it would be able to service only one client at a time. So, other clients may have to wait for its request to be serviced.

One solution to run a server as a single process which accepts requests is that the server receives a request, which creates a separate process to service that request. Process creation is time consuming and resource intensive.

So, it is generally more efficient to use one process that contains multiple threads. This is known as a multi thread process. The web server would create separate thread that would listen for client requests rather creating another process.

Benefits of multithreading

The benefits of multithreading are as follows −

Responsiveness

Multithreading is an interactive application that allows a program to continue running even though the parts are blocked or is performing a lengthy operation, thereby increasing responsiveness to the user.

Resource sharing

Generally, a thread shares the memory and the resources of the process that it belongs to. It is allowed as an application to have several different threads of activity within the same address space.

Economy

Allocating memory and resources for process creation is costly because threads share resources of the process to which they belong. It is more economical to create and context switch threads.

Utilization of multiprocessor architectures

Multithreading can be greatly increased in multiprocessor architecture where threads may be running in parallel on different processors. A single thread can run only on one CPU. Multithreading increases concurrency.

raja
Updated on 30-Nov-2021 12:13:18

Advertisements